Attach event to dynamically created chosen select using jQuery

蓝咒 提交于 2019-12-11 09:19:23

问题


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>

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




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


来源:https://stackoverflow.com/questions/24412158/attach-event-to-dynamically-created-chosen-select-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!