Possible Duplicate:
Set attribute without value
Sometimes, when handling with HTML, it is required to set an attribute of a DOM element without using any value, e.g. see the selected
parameter here:
<select id="auto-makers">
...
<option value="fiat" selected>FIAT</option>
<option value="ford">FORD Motor Company</option>
<option value="gm">General Motors</option>
...
</select>
This kind of attributes in HTML documents are a not rare. For instance, here follows a list of possible attributes:
checked
;selected
;required
;multiple
;disabled
;How can I set a property with no value at runtime using Javascript and/or jQuery?
Following your example, suppose that you have
<select id="auto-makers">
...
<option value="fiat">FIAT</option>
<option value="ford">FORD Motor Company</option>
<option value="gm">General Motors</option>
...
</select>
and that you want to add the selected
attribute to the <option>
such that value="fiat"
. Hence, with pure Javascript you can use setAttribute
method:
var select = document.getElementsById('auto-makers');
for (var i=0; i<select.options.length; i++){
if (select.options[i].value=="fiat"){
select.options[i].setAttribute('selected','');
break;
}
}
while with jQuery you can simply use the attr
method:
$('#auto-makers').find('option[value="fiat"]').attr('selected','');
In both cases, an empty string is passed as value for the attribute.
You can verify that the output is the one desired by looking at the related HTML code just after the changes you provided.
Finally, notice that a similar question is: "Set attribute without value".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With