Puzzled by DOM behavior dynamically loaded select = undefined
-
12-11-2019 - |
Question
Below is the following code that works perfectly for dynamic loading of a select drop down. The code is called in the documents ready function to pre-load data into a page. The code works just fine. However, I got puzzled over the fact that it seems "undefined" in the DOM. ie.. .change event etc...when I attempt to select a value....
In the HTML, the is set simply:
<select id="optionsChaa" name="chaa_id" class="largewidth"></select>
The jquery code is as follows. It works. Feel free to use it in your codes
var optionsValues = '<select id="optionsChaa" name="chaa_id" class="largewidth">';
optionsValues += '<option value=""></option>';
$.each(result, function() {
optionsValues += '<option value="' + this.chaa_id.val + '">' + this.chaa_name + '</option>';
});
optionsValues += '</select>';
var options = $('#optionsChaa');
options.replaceWith(optionsValues);
$('#optionsChaa').change(function() {
// Alert returns undefined...
alert($(this).val() );
});
So why is it "undefined" after the DOM?
No correct solution
OTHER TIPS
I think there's something wrong with the this.chaa_id.val
part. In each
, "this" refers to the "current" element (i.e. a member of the results
array).
Could you show what's in your result
variable?
I tried your code setting result
as:
var result = [
{ 'chaa_id' : { 'val' : 1 }, 'chaa_name' : 'name1'},
{ 'chaa_id' : { 'val' : 2 }, 'chaa_name' : 'name2'}
]
And the alert()
seems to work.