undefinedfix
Sign in

How to get the selected items under multiple select with the same ID

Zlotz edited in Fri, 11 Nov 2022

Excuse me, I have the following code

<select id="rwid1">
  <option id="1">首页</option>
  <option id="2">次页</option>
  <option id="3">末页</option>
</select>
<select id="rwid1">
  <option id="1">首页</option>
  <option id="2">次页</option>
  <option id="3">末页</option>
</select>
<select id="rwid1">
  <option id="1">首页</option>
  <option id="2">次页</option>
  <option id="3">末页</option>
</select>

How to get the selected items of each select?

<script>
  $('#rwid1').each(() => {
    $(this).on('change', (e) => {
      console.log(e.target)
    })
  })
</script>

I have tried to use the above method, but I can only get the current select. I really don't know how to get the selected items under each select? Thanks for your advice!

4 Replies
PitStorm
commented on Fri, 11 Nov 2022

Change the ID of select tag in HTML to class

 $('.rwid1').each(function(){
   $(this).on('change', (e) => {
      console.log(e.target.selectedOptions[0].value)
   })
})`
martingaryulo
commented on Fri, 11 Nov 2022

Shouldn't Id be unique

faza
commented on Sat, 12 Nov 2022

The ID selector will only find the first matching item, even if $('#################id'). Each() can only get the first matching item. If you have to use the same ID to define the label, you can use the label selector

$('select[id]').change(function() {
    console.log(this.value);
});

Of course, even if this method is used, it is not easy to distinguish which < Select > value has been changed. Some auxiliary tools are needed (using index tag / business tag, etc.):

$('select[id]').change(function() {
    var $this = $(this);
    console.log($this.index()); // 1. 确定索引不会改变
    
    // 或者通过业务标记来区分
    // this.dataset.key
    $this.attr('data-key'); 
});


$('select[id]').each(function(){
    // 2. select应该是动态生成的, 可以为每个select添加业务标记
    $(this).attr('data-key', busUniqueKey); 
});
AfajarS
commented on Sat, 12 Nov 2022

Well, ID can be used repeatedly. What do you want