javascriptjqueryasp.netjquery-eventsjquery-chosen

Chosen dropdown is holding focus


I have a dropdown list that implements the Chosen plugin. When an option is selected, the cursor is supposed to be put in a textbox on the same page. I'm trying to use the onChange attribute of the dropdown to accomplish this, but it isn't working. The onChange event is being fired, but the focus stays on the dropdown.

When I disable Chosen, it works perfectly. So I know it has something to do with the plugin, but I don't know what the exact problem is.

Why is the Chosen dropdown preventing jQuery from switching the focus?

The relevant HTML:

<!--Unrelated code has been removed--> 
<div class="mws-form-col-8-8 ">
    <div class="mws-form-item large">
    @Html.DropDownList("addOtherProvision" + chargeId, Model.otherProvisionDropdown, "",
                           new { onchange = "$('#additionalDetails').focus();", 
                                 id = "addOtherProvision" + chargeId })
    </div>
</div>

<div id= "@(chargeId)otherProvisionDialog" class="mws-panel-body"
    title="Add Additional Details">
    <div class="mws-form-cols clearfix">
        <div class="mws-form-item large">
            @Html.TextBox("additionalDetails", "", new {id = "additionalDetails", 
                           @class = "mws-textinput" })
        </div>
    </div>
</div>

Solution

  • Seems like this has been an issue with the last couple of versions. These have been addressed Here and mainly Here. The workaround simply adds a setTimeout that removes the selected class from the Chosen element, and waits a little bit (enough for the next loop to execute) and focuses then:

    $("select").chosen().on('change', function(evt, params) {
        setTimeout(function(){
            $(this).removeClass('chosen-container-active');
            $('#additionalDetails').focus();
        }, 0);
    });
    

    Given the nature of your markup (you are using Razor) I would suggest having this in your JavaScript instead to improve readability.

    JSFiddle: http://jsfiddle.net/q22vy16j/