Binding event to chosen select

余生颓废 提交于 2019-12-21 07:00:40

问题


I have this code for a select box which is being displayed by the Chosen jQuery plugin. What I am trying to achieve is to get the value from the current item that has been selected:

<div>
  <select id="schedule_event" name="schedule[event]" style="display: none; " class="chzn-done"><option value="Game" selected="selected">Game</option>
    <option value="Event">Event</option>
    <option value="Training">Training</option>
  </select>
  <div id="schedule_event_chzn" class="chzn-container chzn-container-single chzn-container-active" style="width: 854px; ">
    <a href="javascript:void(0)" class="chzn-single chzn-single-with-drop" tabindex="-1">
      <span>Game</span>
      <div></div>
    </a>
    <div class="chzn-drop" style="width: 849px; top: 27px; left: 0px; ">
      <div class="chzn-search">
        <input type="text" autocomplete="off" style="width: 814px; " tabindex="0">
    </div>
    <ul class="chzn-results">
      <li id="schedule_event_chzn_o_0" class="active-result result-selected highlighted" style="">Game</li>
      <li id="schedule_event_chzn_o_1" class="active-result" style="">Event</li>
      <li id="schedule_event_chzn_o_2" class="active-result" style="">Training</li>
    </ul>
  </div>
</div>
</div>

The JavaScript I'm using at the moment to find the current value is:

$("#schedule_event").chosen().change( function() {
    alert(+ $(this).text());
    $('#' + $(this).val()).show();
});

However, I keep getting a 'NaN', ie no value.


回答1:


Code:

$(".chzn-select").chosen().change(function() {
    alert(+$(this).val());
    //$('#' + $(this).val()).show();
});

Demo:

Working demo: http://jsfiddle.net/MM7wh/

Edit (6th July 2015)

cdns are changed now.

Working demo: http://jsfiddle.net/uk82dm5L/

Please use $(this).val() instead of .text().




回答2:


Personally I prefer use this:

$(document).on('change', '#mychosen', function(evt, params) {
    if (params.selected != undefined)
    {
        console.log('selected: ' + params.selected);
    }
    if (params.deselected != undefined)
    {
        console.log('deselected: ' + params.deselected);
    }
});


来源:https://stackoverflow.com/questions/11279898/binding-event-to-chosen-select

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