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&...

问题:

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.

  • 发表于 2019-01-22 20:57
  • 阅读 ( 178 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除