使用jQuery禁用select中的一些选项

时间:2014-07-17 04:25:59

标签: javascript jquery

我有以下HTML代码:

<select class="pointSelect" id="mySelect" tabindex="2" name="mySelect">
  <option value="01" selected="selected">Choose Country</option>
  <option>United States</option>
  <option>Canada</option>
  <option>United Kingdom</option>
  <option>Czech Republic</option>
  <option>Any other Country</option>
</select>

<select class="pointSelect" id="mySelect1" tabindex="3" name="mySelect1">
  <option value="nothing" selected="selected">Choose Shipping Options</option>
  <option>Free Shipping</option>
  <option>Registered Airmail</option>
  <option>Express Shipping</option>
</select>

以及以下jQuery代码:

$("#mySelect").change(function() {
  debugger;
  var index = $(this).find("option:selected").index();
  $("#mySelect1").find("option:lt("+index+")").attr("disabled","disabled");
  $("#mySelect1").find("option:gt("+index+")").removeAttr("disabled");
});

Demo jsFiddle

我如何仅针对“其他任何国家/地区”禁用免费送货。

4 个答案:

答案 0 :(得分:2)

在Jquery中使用Prop来禁用该选项。如果你使用attr你不能再启用和禁用选项

   $("#mySelect1").prop("disabled", true);
   $("#mySelect").change(function () {
         $("#mySelect1").prop("disabled", (this.value == '01'));
         $("#mySelect1").find("option:eq(1)").prop("disabled", (this.value == 'Any other Country'));
     });

DEMO

NEW UPDATED DEMO

答案 1 :(得分:1)

你可以使用如下所示的.prop()(我怀疑它会在IE中运行)

$("#mySelect").change(function () {
    var disable = $(this).val() == 'Any other Country';
    $("#mySelect1").find("option:contains(Free Shipping)").prop("disabled", disable);
});

演示:Fiddle

另一种方法是删除该选项,而不是禁用它like here

$("#mySelect").change(function () {
    var freeShipping = $(this).val() != 'Any other Country';
    if (freeShipping) {
        if (!$("#mySelect1").find("option:contains(Free Shipping)").length) {
            $("#mySelect1 option:first-child").after("<option>Free Shipping</option>");
        }
    } else {
        $("#mySelect1").find("option:contains(Free Shipping)").remove();
    }

});

答案 2 :(得分:0)

试试这个

禁用运费 HTML

<select disabled="disabled" class="pointSelect" id="mySelect1" tabindex="3" name="mySelect1">

脚本

 $("#mySelect").change(function () {
    $("#mySelect1").removeAttr("disabled")
    var text = $(this).find("option:selected").text();
    if (text == 'Any other Country') {
        $("#mySelect1").find("option:eq(1)").attr("disabled", "disabled");
    } else {
        $("#mySelect1").find("option").removeAttr("disabled")
    }
    });

DEMO

答案 3 :(得分:0)

在更改功能之前使用以下内容:

$("#mySelect option:last").prop('disabled','disabled');

fiddle

相关问题