I'm using jQuery Chosen on my page and I want to run a function every time a new option is selected. The function hides all of the child div
s in a parent div
, then shows just the one that corresponds to the option that was selected.
HTML:
<select id="settings-select" data-placeholder="Choose…" class="chzn-select">
<option value="setting1">Option 1</option>
<option value="setting2">Option 2</option>
<option value="setting3">Option 3</option>
<option value="setting4">Option 4</option>
<option value="setting5">Option 5</option>
<option value="setting6">Option 6</option>
</select>
<div id="settings-tabs">
<div id="setting1" class="tab">...</div>
<div id="setting2" class="tab">...</div>
<div id="setting3" class="tab">...</div>
<div id="setting4" class="tab">...</div>
<div id="setting5" class="tab">...</div>
<div id="setting6" class="tab">...</div>
</div>
JS:
var settingsShow = function(){
var showPanel = $("#settings-select").find('option:selected').val();
$("#settings-tabs .tab").hide();
$("#" + showPanel).fadeIn("fast");
alert(showPanel);
}
$(document).ready(function(){
$("#settings-tabs .tab").hide();
$("#settings-select").chosen().change(settingsShow);
});
All of this works fine so far – when the selected item is changed, settingsShow
is called (and an alert displays just to confirm this).
Now, I also have an AJAX call that changes the selected option when it completes:
$("#settings-select").val("setting1").trigger("liszt:updated");
settingsShow();
Here's the problem: once the selected option is changed by the completed AJAX call, selecting the previously-selected option no longer fires the change event. For example:
- Select "Option 2": displays alert "option2"
- Perform AJAX call: upon completion, selects "Option 1" and displays alert "option1"
- Select "Option 2": nothing happens
I know it's an issue with Chosen specifically because it works fine if I use a normal select
instead (at step 3 above, I'll get an alert that says "option2", like I should). But as you can see, I'm using .trigger("liszt:updated")
to update the select
when the AJAX call changes the selected option, so I don't see why this doesn't work.