Reputation: 11330
I am a newbie with Jquery and i am trying to append an select option. This works and when i select the newly added option in the select. I am getting undefined in alert.
var selects = $(this).closest('div').find('.accSelectandlookup') ;
//Check if the accid is already present in the selectoptions and if not then add
if (!selects.find('option[value="' + accid + '"]').length) {
alert(accid); // This throws up the correct value
selects.append('<option value="' + accid + '">Attach to Existing : ' + accname + '</option>');
}
What am i doing wrong ?
Thanks in advance
selects.change(function(){
alert('selected value is ' + selects.filter(":selected").val()); // This throws undefined
})
Upvotes: 0
Views: 507
Reputation: 5263
When you load the .change()
function, it reads the current DOM.
When you append
, it's changing the DOM, but that doesn't update what .change()
is looking at. So you need to modify it like so...
$('body').change(function(){
alert('blah');
}, '.accSelectandlookup');
This keeps .change()
LIVE, using the current DOM.
Upvotes: 1
Reputation: 148160
Simply use $(this).val(
) to get the selected option
value of current select
. The selects
might not be available when change
event is fired due to variable scope.
selects.change(function(){
alert('selected value is ' + $(this).val()); // This throws undefined
});
Upvotes: 1