Reputation: 59
I just want to do something very simple, which is a select depending on which option is selected it populates a second select.
I've always done this by hiding/showing selects this way (JS):
$( document ).ready(function() {
$("#select_1").change(function() {
if ($("#select_1").val()=="A") {
$("#select_2").show();
$("#select_3").hide();
}
else if ($("#select_1").val()=="B") {
$("#select_3").show();
$("#select_2").hide();
};
});
But now I'm trying Chosen and it does not work. It removes all Chosen mask and returns the selects to native. I've also tried this (JS):
$(document).ready(function(e) {
$("#select_2").css('visibility','hidden');
$(".chosen").chosen();
$("#select_1").click(function() {
if ($("#select_1").val()=="A") {
$("#select_2").css('visibility','visible');
}
And it doesn't work either. It does not remove the Chosen, but doesn't do anything. Any idea on this? I know it sounds pretty basic by I couldn't find an accurate response to it anywhere.
PS: I'm trying to do it with JS, not via AJAX.
Upvotes: 1
Views: 1874
Reputation: 9003
I'm assuming that #select_1 is to have the chosen plugin applied to it. If this is correct, #select_1 is going to have a style of display:none; applied to it, so you not going to register any 'click' events on it.
If you look at the "chosen" documentation, http://harvesthq.github.io/chosen/, you can discover how to register a change handler to your chosen element.
If chosen is applied to #select_2 and #select_3, then toggling the visibility of these two elements is pointless because they are already hidden. The HTML rendered by the chosen plugin will have container elements with IDs of #select_2_chosen and #select_3_chosen - so toggle the visibility of these!
The code below assumes that #select_2 and #select_3 have the class 'chosen'. I am applying the chosen to #select_1 separately so I can bind the change event that is to be unique to it. Finally, I trigger the change event immediately after defining the change handler so that #select_3_chosen will become hidden.
$(".chosen").chosen();
$("#select_1").chosen().change(function () {
var value = $(this).val();
if (value=="A") {
$("#select_2_chosen").css('visibility','visible');
$("#select_3_chosen").css('visibility','hidden');
} else if (value == "B") {
$("#select_2_chosen").css('visibility','hidden');
$("#select_3_chosen").css('visibility','visible');
}
}).trigger('change');
Upvotes: 1