Prady
Prady

Reputation: 11330

After appending a select option and selecting the appended option alert shows undefined + Jquery

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

Answers (2)

designosis
designosis

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

Adil
Adil

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

Related Questions