Reputation: 36
I'm pretty new to jQuery and javascript so go easy on me. I have a select box with the id="select-cat". This select box is being created dynamically so I went ahead and used the .on event handler like so:
$(document.body).on('change', '#select-cat', function() {
});
My problem arises when I try to get the option value. Here are a few things that I've tried:
var x = this.value; //doesnt work, I'm assuming in this case "this" refers to document.body
$('#select-cat').on('change', function() { //"this" works, but event isn't added to dynamically created elements
var x = this.value;
});
Does anyone have a method I could use to keep this event handler on dynamic elements while still being able to pull their values?
Upvotes: 0
Views: 130
Reputation: 4207
Use this:
$('body').on('change', '#select-cat', function() {
var value = $(this).find('option:selected').val();
// do something with the value..
});
The select box itself doesn't have a val, the 'selected' option has a value
Upvotes: 0
Reputation: 12040
Check out .on using: jQuery Documentation
$(document).on('change', '#select-cat', function() {
var x = this.value;
});
Upvotes: 1