Puzzled by DOM behavior dynamically loaded select = undefined-Collection of common programming errors

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:


The jquery code is as follows. It works. Feel free to use it in your codes

var optionsValues = '';
                optionsValues += '';
                $.each(result, function() {
                    optionsValues += '' + this.chaa_name + '';
                });
                optionsValues += '';

                var options = $('#optionsChaa');
                options.replaceWith(optionsValues);

                $('#optionsChaa').change(function() {

                   // Alert returns undefined...

                    alert($(this).val() );

                });

So why is it “undefined” after the DOM?

  1. 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).

  2. 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.

Originally posted 2013-11-09 22:47:59.