I'm fixing a horrendous bug in an old web application. For some datasets, the values in an option/select list are unfortunately not unique. But luckily, the custom attribute test
is unique.
So I have the following HTML structure:
<select id="dropdown">
<option value="1" test="A">fooA</option>
<option value="2" test="B">fooB</option>
<option value="2" test="C">fooC</option>
<option value="2" test="D">fooD</option>
<option value="2" test="E">fooE</option>
</select>
So I wonder how could set C
from the custom attribute test
with the help of Jquery or vanilla JS in the select/dropdown field? The .attr()
property only changes the properties of the custom attribute test
, which I not want. I want to set fooC
in the select field.
JSFiddle link to try: /
I'm fixing a horrendous bug in an old web application. For some datasets, the values in an option/select list are unfortunately not unique. But luckily, the custom attribute test
is unique.
So I have the following HTML structure:
<select id="dropdown">
<option value="1" test="A">fooA</option>
<option value="2" test="B">fooB</option>
<option value="2" test="C">fooC</option>
<option value="2" test="D">fooD</option>
<option value="2" test="E">fooE</option>
</select>
So I wonder how could set C
from the custom attribute test
with the help of Jquery or vanilla JS in the select/dropdown field? The .attr()
property only changes the properties of the custom attribute test
, which I not want. I want to set fooC
in the select field.
JSFiddle link to try: http://jsfiddle/rnnfk/120/
Share Improve this question asked Mar 22, 2016 at 11:53 ReneFrogerReneFroger 5309 silver badges21 bronze badges 1- If you want to display the test attribute text as the option without showing duplicate values..then try this demo – Lucky Commented Mar 22, 2016 at 12:01
3 Answers
Reset to default 4First you need to select the attribute with the help of css attribute selector then add selected
attribute using attr().
Try this technique. Demo
$('#dropdown option[test=C]').attr( "selected","selected");
You can use attribute selector to get the option with attribute test with specific value.
Live Demo
$('#dropdown option[test=C]').prop('selected', true);
Just add following code in jquery :-
$("#dropdown [test='C']").attr("selected", "selected");
It may help you.