Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining selects with Chosen

I'm trying to chain selects with Chosen and Chained but I'm not sure if I'm implementing .chosen().change() correctly or if the error I'm getting is a bug.

Here's what I've got:

<select id="Inputfield_date" name="date" data-placeholder="Select event date">
<option value=""></option>
<option value="WA">WA</option>
<option value="QLD">QLD</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="SA">SA</option>
</select>

<select id="Inputfield_code" name="code" data-placeholder="Response code">
<option value=""></option>
<option value="601" class="WA">601</option>
<option value="602" class="WA">602</option>
<option value="402" class="QLD">402</option>
<option value="403" class="QLD">403</option>
<option value="301" class="VIC">301</option>
<option value="302" class="VIC">302</option>
<option value="201" class="NSW">201</option>
<option value="203" class="NSW">203</option>
<option value="501" class="SA">501</option>
</select>

$('#Inputfield_date').chosen().change(function() {
    $("#Inputfield_code").chained("#Inputfield_date");
});

which gives me Uncaught RangeError: Maximum call stack size exceeded.

EDIT: I now also need to hide/show another field if a particular option is chosen and I'm not sure what the correct approach is for that.

like image 341
Tyssen Avatar asked Aug 26 '13 09:08

Tyssen


1 Answers

Using the example from the Chained documentation I've put up an example on jsfiddle.

And it is actually fairly simple, just initialize Chained and Chosen as you would normally do, and then trigger the chosen:updated event if one of the selects changes:

var selects = $('#Inputfield_code, #Inputfield_date');
$('#Inputfield_code').chained('#Inputfield_date');
selects.chosen({width: '300px'})

selects.on('change', function(){
    selects.trigger('chosen:updated');
});

EDIT:

For your second question I've updated the fiddle a bit: http://jsfiddle.net/koenpunt/Fzh9G/2/

Chosen sends which option is selected alongside the change event, so checking if a specific option is selected is easy:

$('#series').on('change', function(event, data){
    // First check if data exists, because if the change event
    // isn't triggered by Chosen `data` is undefined
    if(data){ 
        if(data.selected == 'a5'){
            $('#submit').hide();
        }else{
            $('#submit').show();
        }
    }
});

As you will notice, if you select 'Audi' and 'A5' the button will disappear.

like image 144
Koen. Avatar answered Sep 30 '22 05:09

Koen.