简体   繁体   中英

Resetting a chosen select box with javascript

I'm having problems performing action on select boxes that make use of the chosen plugin. it seems fine when using the input of a chosen select box to manipulate a standard HTML select box but when I add the "chzn-select" class to that select box the script falls over.

Here's the code.

HTML:

<form>
    <select id="sel1" name="sel1" class="chzn-select">
        <option value="1">1</option>
        <option value="2">Computer</option>
        <option value="3">3</option>
    </select>

    <div id="select2" style="display:none">
        <select id="sel2" name="sel2" selected="selected" class="chzn-select">Select
           <option value=""></option>
           <option value="1">1</option>
           <option value="2">2</option>
           <option value="3">3</option>
         </select>
    </div>
</form>

The javascript:

$(function () {
    var selCategory = $('#sel1');
    selCategory.change(function () {
        selCategory.find('option:selected').each(function () {
            if ($(this).text() ==='Computer') {
                $('#select2').show();
            }
        else{
            $('#select2').hide();
        }
        });
    });
});

$('#sel1').on('change', function () {
     $('#sel2').prop('selectedIndex',0);
});

Any indication on where I'm going wrong would be much appreciated!

EDIT 11/11/13

I've had some time to figure this out as all the answers that I have received for this question seem to be correct for regular select boxes but not with the chosen plugin. That needs to be updated separately. The fix for that was to add $('#sel2').val('').trigger('chosen:updated'); which resets the chosen select box to its original state. I found the code here How do I reset a jquery-chosen select option with jQuery?

I appreciate all the help you gave me and hope this edit helps anyone who is as confused as I was.

您需要在选项而不是select标记上更改“ selected”属性。

selected属性应在option标签内

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM