Reputation: 331
I have multiple select boxes whithin a form like this:
<form action="foo" method="post" id="form">
<select id="one">
<option value="foo1"></option>
<option value="foo2"></option>
<option value="foo3"></option>
</select>
<select id="two">
<option value="bar1"></option>
<option value="bar2"></option>
<option value="bar3"></option>
</select>
<select id="three">
<option value="baz1"></option>
<option value="baz2"></option>
<option value="baz3"></option>
</select>
</form>
Now, if any of these three boxes change, I wanna know which one of them. I tried it like the following, but I only get the id of the first box. Do I have to write it for each select or is there a way to get the id of the changed select box?
$(document).ready(function() {
$('#form').change(function() {
var strChosen = $('select').attr('id');
alert(strChosen);
});
});
Upvotes: 2
Views: 11457
Reputation: 157394
Use this
keyword and change your selector to $('#form select')
$(document).ready(function() {
$('#form select').change(function() {
var strChosen = $(this).attr('id');
alert(strChosen);
});
});
Note: You can also use .on()
method for change
event like
$('#form select').on('change',function() {});
For more information on the syntax, you can refer @sbaaaang's answer
Upvotes: 6
Reputation: 455
first thing is that you need to bind the change event of the select box instead of form like that :
$(document).ready(function(){
$('select').change(function (e){
});
});
then you are able to find the id of changed select box putting below code inside the change handler.
var selectedId = this.id;
the finale code look like below:
$(document).ready(function(){
$('select').change(function (e){
var selectedId = this.id;
alert(selectedId);
});
});
thanks..
Upvotes: 0
Reputation: 20860
You are using .change() event on form. That's wrong.
Use select element with change event like below.
$(document).ready(function() {
$('select').change(function() {
var strChosen = $(this).attr('id');
alert(strChosen);
});
Here is the working demo : http://jsfiddle.net/n46Be/
Upvotes: 0
Reputation: 388416
Register the change handler for the select
element then inside the handler use this.id
to get the id of the select element
$(document).ready(function () {
$('#form select').change(function () {
var strChosen = this.id;
alert(strChosen);
});
});
Demo: Fiddle
Upvotes: 0
Reputation: 49853
$(function(){
$('select').on('change',function(){
var id = $(this).attr('id');
alert(id);
});
});
Upvotes: 3