Developer Desk
Developer Desk

Reputation: 2344

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 jquery.live or jquery.on event but for that we need proper selector/id

$(document).on( eventName, selector, function(){} );

My fiddle : Demo Fiddle

html :

<select id="t1pl1" class="chosen-select" data-placeholder="Select player..." style="width:200px;">
    <option value="0"></option>
    <option value="11">Player 1</option>
    <option value="12">Player 2</option>
    <option value="13">Player 3</option>
</select>

Upvotes: 1

Views: 2187

Answers (2)

K K
K K

Reputation: 18099

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()

Upvotes: 3

Ingmars
Ingmars

Reputation: 998

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.
});

Upvotes: 0

Related Questions