Search code examples
javascriptjqueryclassonchangedropdownbox

DropDownList: call class method by changing


my problem is the following:

  • I create a class for a dropt-down list, with a methode to create the drop-down-list
  • I want to call an other methode "select_entry_in_list" when the user select an other entry in the list

But that's not working in this way.

I try it at following way:Link www.w3schools.com - editor

// track the change event - jquery
$('#xv_select_typ').on('change', function() {
      this.obj_opt.select_entry_in_list();
});​

// called by a Button (onclick)
function create(){
    this.obj_opt = new opt();
    this.obj_opt.create_option_list();
}​

// Option list class
class opt {    

    // create the option list
    create_option_list(){ 

        var list_entrys = [
            [1,"Hallo"],
            [3,"buongiorno"],
            [5,"bonjour"]
        ];

        var list = "<select id='xv_select_typ'>";
        var opt_entry;

        list = list + "<option>-</option>";

        for (var key in list_entrys) {  

          var entry_name = list_entrys[key][1];
          opt_entry = "<option entry_id='"+key+"'>"                 
            + entry_name   
            + "</option>";
          list = list + opt_entry;​
        }
        list = list + "</select>"; 

        $('#sec').html(list);
    }  

    // When an entry of the list will changed
    select_entry_in_list(){
        alert("WORK!");
    }

}

Solution

  • Move the select event handler into the create function like this:

        // called by Button
    function create(){
        self.obj_opt = new opt();
        self.obj_opt.create_option_list();
            // track the change event
    $('#xv_select_typ').on('change', function() {
          self.obj_opt.select_entry_in_list();
    });
    
    }