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!
Change the ID of select tag in HTML to class
$('.rwid1').each(function(){
$(this).on('change', (e) => {
console.log(e.target.selectedOptions[0].value)
})
})`
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);
});