简体   繁体   中英

How to disable particular item in a drop down element

如何使用jQuery或JavaScript禁用下拉元素的某些项?

The same way you would disable any other HTML element, use

$(/* option selector */).prop('disabled', true);

See it in action .

Easy!

<select>
  <option value="Opt 1.">Opt 1.</option>
  <option class="optionselector" value="Opt 2. I'm disabled!" disabled="disabled">opt 2. I'm disabled!</option>
</select>

Simply append disabled="disabled" in the tag.

To do it in jQuery, make sure you've got the latest version loaded, then use the .attr() javascript to append the attribute disabled="disabled" as needed like so:

.click(function(){
    $('.optionselector').attr("disabled","disabled");
});

Of course, you'll have to put .click inside of another event or function, so the .click is triggered by SOMETHING in particular, such as, this can be used to say "When I .click() this button, then add .attr()" etc.

Lots of jQuery, in plain js you get a reference to the option however and just set the disabled property to true. So given:

<form id="aForm" ...>
  <select name="aSelect">
    <option ...>zero
    <option ...>one
    <option ...>two
    <option ...>three
  </select>
  ...
</form>

then to disable all the options:

var options = document.forms['aForm']['aSelect'].options;
for (var i=0, iLen=options.length; i<iLen; i++) {
  options[i].disabled = true;
}

Of course you can disable just one based on whatever criterion you want.

$(document).ready(function(){   
     $('#id').attr('disabled','disabled');          
})

and the html

<form id="fmname" method="get">

<select >
<option id="id">s</option>
</select>
<input type="submit" />

</form>
$("option").attr("disabled", "disabled");

只需使用其他选择器选择所需选项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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