开发者

Trying to enable/disable an input text when a chekbox is unchecked/checked

I'm trying to enable/diable an input text when a chekbox is checked/unchecked

I have tried this below but it doesn't work..

  $('#checkbox').change(function(){


    if($('#name').attr('disabled') == 'true')
      $('#name').attr('disabled', 'false');
    else
      $('#name').attr('disabled', 'true');

  })开发者_JS百科;

Any help?

Regards

Javi


You're setting the "disabled" attribute to true in both cases. Try this instead:

if($('#name').attr('disabled'))
  $('#name').attr('disabled', false);
else
  $('#name').attr('disabled', true);

Or, more simply:

 $('#name').attr('disabled', !$('#name').attr('disabled'));

The strings you used — "true" and "false" — are both true values to JavaScript. They're non-empty strings, and that's all that matters. When you use the real constants true and false, you get what you intended.

The common practice of using "disabled" as the true value for the attribute is a silly superstition that has no basis in fact. It does work, of course, because "disabled" is also a non-empty string, and so it's true. You could use null for the false value if you wanted to, or a numeric zero.

edit — fixed the if statement as per the helpful comment. All that's necessary is to check the truthiness of the attribute.


The disabled attribute should have this value: disabled or empty string instead of true and false.

if($('#name').attr('disabled') == 'disabled')
    $('#name').attr('disabled', '');
else
    $('#name').attr('disabled', 'disabled');


Try this :

if($('#name').attr('disabled'))
    $('#name').removeAttr("disabled");
else
    $('#name').attr("disabled", true);

Check if attribute exists and removes it, else adds attribute


$('#checkbox').change(function() {

    if ($('#checkbox').is(':checked')) {
        $('#name').removeAttr('disabled');
    } else {
        $('#name').attr('disabled', 'disabled');
    }

});


From jquery 1.6.1 -> rather use:

$("#checkbox").change(function(){
    if($("#checkbox").checked)
        $("#name").prop("disabled", false);
    else
        $("#name").prop("disabled", true);

});

i.e. use prop instead of attr ( http://api.jquery.com/prop/ )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜