简体   繁体   English

用javascript重置选定的选择框

[英]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. 使用选择的选择框的输入操作标准HTML选择框时似乎很好,但是当我将"chzn-select"类添加到该选择框时,脚本将"chzn-select"

Here's the code. 这是代码。

HTML: 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: 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 编辑13/11/11

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'); 解决方法是添加$('#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? 我在这里找到了代码如何使用jQuery重置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标签内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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