1

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>
Developer Desk
  • 1,981
  • 7
  • 32
  • 69

2 Answers2

3

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

K K
  • 16,034
  • 4
  • 25
  • 37
  • How are you getting the value in $('#pid') ? What is the logic behind it? – K K Jun 25 '14 at 15:18
  • actually team has 11 players so there are 11 constant chosen select box but if user wants to add more player/referee then he will enter how many persons he wants to add in $("#t1pladdcount") text default is 1 – Developer Desk Jun 25 '14 at 15:22
  • $("#pid") contains option value using this value i want to show photo of player or referee later on option hover/mouseover event – Developer Desk Jun 25 '14 at 15:23
  • Okay, check the updated answer. See if it works for you. – K K Jun 25 '14 at 15:28
  • it conflicts as my page has many chosen select box....so i added "player" class to each select tag... – Developer Desk Jun 25 '14 at 16:22
  • i used `$(document).on('mouseenter', 'li.active-result.highlighted', function (e) { var currentText = $(this).text(); showplayer ($(document).find("select.player option").filter(function () { return $(this).html() == currentText; }).val()) });` – Developer Desk Jun 25 '14 at 16:23
  • Better give a common class to the select. I just displayed how it is done. You can modify accordingly. – K K Jun 25 '14 at 16:24
0

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.
});
Ingmars
  • 938
  • 5
  • 10