Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make all options enabled in select element

I have a dropdown with a few disabled options. And I want make all options enabled.

This is html:

<select id="selectId">
    <option value="JavaScript" disabled="">JavaScript</option>
    <option value="Angular">Angular</option>
    <option value="Backbone" disabled="">Backbone</option>
</select>

JavaScript:

var select = $("#selectId");
select.find("option").each(function(index, item) {
  item.attr('disabled',false);
});

But I get an error: TypeError: item.attr is not a function. What's wrong here?

like image 576
user2598794 Avatar asked May 29 '26 16:05

user2598794


1 Answers

The correct way to alter properties (disabaled is a property not an attribute) is to use prop, see .prop() vs .attr():

$("#selectId option").prop('disabled', false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="selectId">
    <option value="JavaScript" disabled="">JavaScript</option>
    <option value="Angular">Angular</option>
    <option value="Backbone" disabled="">Backbone</option>
</select>

You can set .attr('disabled',false); but this doesn't work on every HTML element. The correct way to remove properties (disabled is a property and not an attribute) is prop.

Your each also doesn't return a jquery object, it returns a vanilla DOM element, hence the TypeError: item.attr is not a function.. item does not have a attr function because it's not a jquery object.

like image 145
Liam Avatar answered May 31 '26 07:05

Liam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!