简体   繁体   中英

put disabled selected attribute into a match value of the select box from a variable

I have this select box (refer below)

<select name="test">
    <option value="option1" disabled selected">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
</select>

and this jquery code (refer below)

var valueofselectbox = "option3";
//loop each option from this select box
$('select option').each(function(){
    //remove all the disabled and selected attribute from all the option within this select box.
    $(this).attr("disabled", "");
    $(this).attr("selected", "");
    //if the variable valueofselectbox is equal to this value then add disabled and selected attribute to this option
    if(valueofselectbox == $(this).val(){
        $(this).attr("disabled selected");
    }
});

Now as you can see from above, first I have a variable name valueofselectbox and then next, I loop through all the options inside that select box and then remove the disabled and selected attribute from each option within that select box and then add disabled and selected attribute if its value (option value) is equal to the varable but seems not working, instead I have this error "Uncaught ReferenceError: selected is not defined" from the console.

You should use

$(this).removeAttr("disabled");
$(this).removeAttr("selected");

from jQuery documentation: http://api.jquery.com/removeattr/

and for setting an Attribute it take 1 attribute name at a time so you can use:

$(this).attr("disabled", "");
$(this).attr("selected", true);

https://api.jquery.com/attr/

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