Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get select tag value from jQuery(document).on('change', ...)

Tags:

jquery

Have one default select box inside a span

Example is here http://jsfiddle.net/pzphbnxb/18/

<span id="all_locations">

<select name="united_kingdom" id="united_kingdom" class="location" >
<option value="blank">Select</option>
<option value="england">England</option>
</select>

</span>    

1) Click on select box and change value.

2) As result get to display next select box

3) If i click on the next select box, i want to alert (for example) id of the clicked select box. But i see alert of the select box above.

Here is jquery

$(document).on('change', '.location', function(){

$('#all_locations').append('<select name="loc_in_england" id="loc_in_england" class="location" ><option value="blank">Select</option><option value="london">London</option>');    

alert ( $('.location').find(":selected").val() + ' selected val' );
alert( $(".location").attr('id') + ' select id' );    

}); //$(document).on('change'    

I mean, i clicked '.location', clicked certain select box, i must get attr('id') of clicked class. Why i get attr('id') of class of the first select box?

Do i need to use something like .closest to get id of clicked select box? If .closest, then closest to what?

like image 501
Andris Avatar asked Dec 15 '14 05:12

Andris


2 Answers

use $(this) instead of $('.location')

$(document).on('change', '.location', function(){  
   //    alert('test');
   $('#all_locations').append('<select name="loc_in_england" id="loc_in_england" class="location" ><option value="blank">Select</option><option value="london">London</option>');   
   alert ( $(this).find(":selected").val() + ' selected val' );
   alert( $(this).attr('id') + ' select id' ); 
}); //$(document).on('change'  

DEMO

like image 129
Mohamed-Yousef Avatar answered Oct 24 '22 20:10

Mohamed-Yousef


http://jsfiddle.net/pzphbnxb/22/

Try this

alert ($(this).find(":selected").val() + ' selected val' );
alert( $(this).attr('id') + ' select id' );
like image 40
SimarjeetSingh Panghlia Avatar answered Oct 24 '22 22:10

SimarjeetSingh Panghlia