Skip to content Skip to sidebar Skip to footer

Attach Event To Dynamically Created Chosen Select Using JQuery

I want to add event to dynamically created chosen select and want to get option value.. but confuse how to fire event on dynamically created chosen select...? I know we can use jqu

Solution 1:

Demo: http://jsfiddle.net/4wCQh/23/

I think you can use on for event binding and since you have dynamic elements, you should use the parent selectors of select for event binding.

Simple solution will be to use this:

    $(document).on('change', 'select[id^="t1"]', function () {
        alert($(this).val());
    });

Use this code for updation:

$(document).on('mouseenter', 'li.active-result.highlighted', function (e) {
   $("#pid").html($("option").eq($(this).data("option-array-index")).val());
});

instead of your old code.

Explanation:

change is the event, select[id^="t1"] is the css selector for all the select having id starting with t1. Refer Attribute Selectors for more information. Further you can get the current value of select using $(this).val()


Solution 2:

To avoid juggling with IDs attach your listeners to the selector itself.

// Do your selectbox creation...
// var selector = whatever...

$( selector ).on( eventName, function( event ){
    console.log( 'Event was triggered by', $( event.target ) );

    // do stuff with your event.target, like getting value and such.
});

Post a Comment for "Attach Event To Dynamically Created Chosen Select Using JQuery"