Chaining selects with Chosen

做~自己de王妃 提交于 2019-12-07 07:32:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18441364/chaining-selects-with-chosen

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