问题:
I have a multiple select like this one could be:
<select multiple id="brand">
<option value="volvo">Volvo</option>
<option value="saab">Saab&...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have a multiple select like this one could be:
<select multiple id="brand">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
And I'm looking for a way to end up like:
<select multiple id="brand">
<option value="volvo" selected="selected">Volvo</option>
<option value="saab" selected="selected">Saab</option>
<option value="opel" selected="selected">Opel</option>
<option value="audi" selected="selected">Audi</option>
</select>
I can't depend on external libraries and I can't make the .each function to work properly. Besides I'm getting the original dinamically set with many fields, and this will be set to this only in a particular case, but i can't figure out why this isn't working for me. The closest approach i found is:
$("#brand").each(function(){$(this).attr("selected","selected");});
Can you please point me out where I'm going wrong? Thanks
回答1:
You need to select the options, for instance with a #brand > option
selector:
$("#brand > option").each(function() {
$(this).attr("selected","selected");
});
console.log($("#brand").html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="brand">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
回答2:
in Vanilla Script you could use something like this
document.querySelectorAll('#brand option').forEach((o)=>{
o.selected = 'selected'
})
If You need IE, be aware that for Each is not supported with node Lists. This should work inkl. IE
nodesArray = [].slice.call(document.querySelectorAll("#brand option"));
nodesArray.forEach(function (o) {
o.selected = 'selected'
})
You wont see the changes in HTML Code, but the DOM Properties of the options will change. Hope this helps.