Tinydan
Tinydan

Reputation: 935

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.

Upvotes: 0

Views: 810

Answers (2)

user2957312
user2957312

Reputation:

property selected should be within the option tag

Upvotes: 1

Christian Fritz
Christian Fritz

Reputation: 21354

You need to change the property "selected" on the options, not on the select tag.

Upvotes: 2

Related Questions