繁体   English   中英

如何使用jQuery在HTML中启用或禁用选择标签?

[英]How do you enable or disable a select tag in html using jQuery?

从jQuery中的第一个选择标签中选择一个选项后,如何启用或禁用选择标签,但当前版本不起作用。

$("select[name='selectALPHA']").change(function () {
    if ($("select[name='selectBRAVO'"].attr('enabled') == false {
      $("select[name='selectBRAVO']").attr('enabled', 'true');
    }
    else
    {
      $("select[name='selectBRAVO']").attr('enabled', 'false');
    }
});

.attr()需要一个布尔值。

$("select[name='selectBRAVO']").attr('disabled', false);

该代码还包含语法错误。 修正:

var $bravo = $("select[name='selectBRAVO']");

$("select[name='selectALPHA']").change(function () {
    $bravo.attr('enabled', !$bravo.attr('enabled'));
});

您似乎想在纯js中切换值:

var select = document.getElementsByName('selectBRAVO')[0];
select.disabled = !select.disabled;

我确定您可以弄清楚jQuery的等效项。

编辑

根据里德的建议,这与马特的做法不同:

var select = $("select[name='selectBRAVO']")[0];
select.disabled = !select.disabled;

旧的jQuery attr方法将HTML属性和DOM属性混为一谈。 在新版本中, attr只处理HTML属性,这更好。 但是,在大多数情况下,程序员真正想要的是DOM属性。 可以直接访问,无需调用attrgetAttribute 直接属性访问(非常快),类型更少且更易于阅读。

我们都知道select元素的属性为disabled

<select disabled="disabled">
</select>

并使用jQuery操作属性值,例如http://api.jquery.com/attr/#attr2上的示例:

$("button:gt(1)").attr("disabled","disabled");

您可以在select元素中执行相同的操作:

$("select[name='selectALPHA']").change(function () {
    if ($("select[name='selectBRAVO'"].attr('disabled') == 'disabled'{
      $("select[name='selectBRAVO']").removeAttr('disabled');
    }
    else
    {
      $("select[name='selectBRAVO']").attr('disabled', 'disabled');
    }
});

我不太确定您要在这里实现什么,但是我认为这可以为您提供帮助:

$("select[name='select1']").change(function () {
    var jSelect2=$("select[name='select2']");

    if($(this).val()){
       jSelect2.removeAttr('disabled');
    }else{
       jSelect2.attr('disabled', 'disabled');
    }

});

在这里查看工作示例: JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM