-2

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?

2
  • Where are you stuck? What exactly do you not know how to do? What have you tried?
    – user1106925
    Sep 8, 2016 at 16:53
  • Show us your html code, and what you tried, so we can help you.
    – M.Hassan
    Sep 8, 2016 at 18:18

3 Answers 3

2

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);
}
2
  • 1
    This is getting the value not the ID and this also wouldn't work for multiple selects "I have many select tags" " I want to get id of select element"
    – NewToJS
    Sep 8, 2016 at 16:52
  • You can also get the id of the select, updated my answer
    – Rob M.
    Sep 8, 2016 at 16:53
2
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
        }
    }
}
8
  • 1
    jsbeautifier.org
    – user1106925
    Sep 8, 2016 at 16:56
  • Don't use onclick, the event will fire when just opening up the select menu, use onchange Sep 8, 2016 at 16:58
  • @squint: using stackexchange app... Sep 8, 2016 at 16:59
  • @Patrick Evans: o yeah right, thank you Sep 8, 2016 at 17:00
  • Thank you, but through events, I more likes
    – mrchebik
    Sep 8, 2016 at 17:02
0

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"));
   })
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.