Reputation: 648
I'm writing a code in which at the document.ready function im creating dynamically some <select>
elements with predefined options, each one with a specific id.
(for example #Select1, #Select2,...).
Each time you press a button you can create a new select element. My question is if there is any way in jquery so each time you select an option to be able see what option ive selected and from which select element? Similiar to the .change()
and option:selected
jQuery functions but with the only difference is that I dont know the id of the element.
Upvotes: 0
Views: 115
Reputation: 87073
$('#container').on('change', 'select[id^=Select]', function() {
// get the select id
console.log(this.id);
// get the select value
console.log(this.value); // or $(this).val();
// To get the selected option's text
console.log($('option:selected', this).text());
});
#container
is the parent of all select
s.
select[id^=Select]
detect all select
, whose id
start with Select
NOTE:
there is nothing like .selected()
in jQuery.
Upvotes: 1
Reputation: 150253
You need to use a delegate event
like with on
:
$('#containerId').on('change', 'select', function(){
this.id // the select id.
this.value // this is the selected option value
$(this).val() // this is the selected option value that works in all browsers
});
This adds a change
callback to every <select>
element under the element with the containerId
id, no matter when they are created.
Upvotes: 2