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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With