简体   繁体   中英

Setting selected attribute for <select multiple> with jquery

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

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> 

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.

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