如何在jQuery中启用/禁用按钮?

5

我的代码看起来像这样:

$("#OperationTypeId").change(function () {
var DropdownSelectionValue = $("#OperationTypeId :selected").val();
    alert(DropdownSelectionValue );
    if (DropdownSelectionValue == 3)
        {
            $("#Button1Id").attr('disabled');
            $(" Button2Id").attr('enable');;
            //$("#Button1Id").hide();
        }
        else {
            $("#Button1Id").attr('enable');
            $(" Button2Id").attr('disabled');;
        }
});

我的代码可以正确显示警报值,但无法根据DropdownSelectionValue的条件使按钮启用/禁用。由于我是初学者,不知道如何做到这一点。请告诉我。

4个回答

6

来自jQuery网站

    Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. 

Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. 

The .prop() method should be used to set disabled and checked instead of the .attr() method.

禁用:

$('#Button1Id').prop('disabled', true);

启用:

$('#Button2Id').prop('disabled', false);

http://api.jquery.com/prop/


5
尝试这个:

试试这个:

$("#OperationTypeId").change(function () {
   var DropdownSelectionValue = $("#OperationTypeId :selected").val();

   if (DropdownSelectionValue == 3) {
     $("#Button1Id").attr('disabled','disabled'); //or $("#Button1Id").prop('disabled',true);
     $("#Button2Id").removeAttr('disabled'); //Use '#' id selector
   }
   else {
     $("#Button1Id").removeAttr('disabled'); // or $("#Button1Id").prop('disabled',false);
     $("#Button2Id").attr('disabled','disabled'); //Use '#' id selector
   }
});

2

禁用

$('#Button1Id').attr('disabled','disabled');

启用

 $('#Button1Id').removeAttr('disabled');

0
你可以使用jQuery的prop来实现相同的功能。
$('#Button1Id').prop('disabled', true);
$('#Button2Id').prop('disabled', false);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接