Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Select ID onchange Jquery

Tags:

jquery

In my application i am trying to get id of select box when accessing onchange function. Here 2 select box are here, both point to same function check.How can i get id of select box when selecting these two select box.ie example1 and example 2.

<select id="example1" onchange='check()'>
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
</select>Example 2 :
<select id="example2" onchange='check()'>
    <option id="1">one</option>
    <option id="2">two</option>
    <option id="3">three</option>
    <option id="4">four</option>
</select>

My Jquery Function, But it only getting id of first select box.

<script>
function check(){
 var id = $('select').attr('id');
 alert(id);
}
</script>
like image 941
Jasir alwafaa Avatar asked Sep 20 '16 13:09

Jasir alwafaa


1 Answers

You need to use $(this)

<script>
    function check(){
         var id = $(this).attr('id');
         alert(id);
    }
</script>

I would suggest you to get rid of inline JavaScript (remove onchange from select elements). And then use this code:

$("select").on("change", function() {
  var id = $(this).attr("id");
  alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="example1">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
</select>Example 2 :
<select id="example2">
    <option id="1">one</option>
    <option id="2">two</option>
    <option id="3">three</option>
    <option id="4">four</option>
</select>

EDIT: I assume that you use jQuery because you wrote $('select') in your question.

like image 112
Vaidas Avatar answered Sep 28 '22 04:09

Vaidas