I have many select
tags, and when user clicks one of the option
tags, I want to get id
of select
element, where clicked on option
.
How I can do this?
I have many select
tags, and when user clicks one of the option
tags, I want to get id
of select
element, where clicked on option
.
How I can do this?
Use the change
event:
document.querySelector('#mySelect').addEventListener('change', function() {
console.log(this.value);
console.log(this.id);
}, false);
<select id="mySelect">
<option value="1">One</option>
<option value="2">Two</option>
</select>
To scale this for multiple elements, define your function outside of the event, iterate over your selects and attach the event listener to them:
function selectChange() {
console.log(this.value);
console.log(this.id);
}
var selects = document.querySelectorAll('select');
for (var i = 0; i < selects.length; i++) {
selects[i].addEventListener('change', selectChange, false);
}
select
s "I have many select tags" " I want to get id of select element"
window.onload=function(){
selects=document.getElememtsByTagName("select");
for(i=0;i<selects.length;i++){
selects[i].onchange=function(){
var select=this.id;
var value=this.value;
var option=this.parentElement.id;
//do whatever
}
}
}
Easy workaround:
<select id="select1">
<option id="o1">1</option>
<option id="o2">2</option>
</select>
<select id="select2">
<option id="o1">3</option>
<option id="o2">4</option>
</select>
<select id="select3">
<option id="o1">5</option>
<option id="o2">6</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
window.onload=function()
{
$(document).on("change","select",function(){
alert($(this).attr("id"));
})
}