Tommy Oliver
Tommy Oliver

Reputation: 81

How to get ID of select when user selected option?

I have 2 select option. Now I want to get id of select when user selected option. Ex: If I selected Option1 then alert id="my_select1" and if I selected MyOption2 then alert id="my_select2". How can I do that?

<select id="my_select1">
  <option value="o1" id="id1">Option1</option>
  <option value="o2" id="id2">Option2</option>
</select>

<select id="my_select2">
  <option value="mo1" id="mid1">MyOption1</option>
  <option value="mo2" id="mid2">MyOption2</option>
</select>

Upvotes: 0

Views: 57

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115282

Bind a change event handler and use this.id to get id of the event fired select tag. Although you can use $(this).attr('id') to get the id attribute value.

$('#my_select1,#my_select2').change(function() {
  alert(this.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="my_select1">
  <option value="o1" id="id1">Option1</option>
  <option value="o2" id="id2">Option2</option>
</select>

<select id="my_select2">
  <option value="mo1" id="mid1">MyOption1</option>
  <option value="mo2" id="mid2">MyOption2</option>
</select>

Upvotes: 0

guradio
guradio

Reputation: 15565

$('select').change(function() {

  alert($(this).attr('id'))//use attr() to get id
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="my_select1">
  <option value="o1" id="id1">Option1</option>
  <option value="o2" id="id2">Option2</option>
</select>

<select id="my_select2">
  <option value="mo1" id="mid1">MyOption1</option>
  <option value="mo2" id="mid2">MyOption2</option>
</select>

  1. Use .attr() to get id
  2. Use $(this) to get the id of the select that made the change

Upvotes: 1

Related Questions