Why does the ASP.net dropdownlist does not default to 0 if chosen jquery is used

时间秒杀一切 提交于 2019-12-12 04:48:37

问题


I was using the Chosen Jquery which causes the dropdownlist to not update.

This is the HTML:

<select name="ctl00$BodyPlaceHolder$ddl1" id="ddl1" class="chose-select le">
    <option value="Select a State">Select a State</option>
    <option value="Alabama">AL</option>
    <option value="Alaska">AK</option>
    <option value="Arizona">AZ</option>
</select>

JavaScript which sets the selected index to 0:

function setSelectedIndex(dropdownlist, selVal) {
    var ddl1 = document.getElementById(dropdownlist);
    if (selVal < ddl1.selectedIndex) {
        ddl1.selectedIndex = selVal;

        $(ddl1).val(0).trigger('chosen:updated');
    }
}

That does the trick with one issue. The issue is once the function sets the selected index to 0, it shows the "Select an Option" as the 0 index instead of the default first option.

Any idea how to fix that?


回答1:


Try something like this:

<select name="ctl00$BodyPlaceHolder$ddl1" id="ddl1" class="chose-select le">
 <option value="" disabled selected>Select a State</option>
     <option value="Alabama">AL</option>
    <option value="Alaska">AK</option>
    <option value="Arizona">AZ</option>
</select>



回答2:


just add data-placeholder="Choose a State" to be like that

<select name="ctl00$BodyPlaceHolder$ddl1" id="ddl1" data-placeholder="Choose a State" class="chose-select le">
    <option value="Alabama">AL</option>
    <option value="Alaska">AK</option>
    <option value="Arizona">AZ</option>
</select>



回答3:


I had to remove the .val(0) and it worked fine.

$(ddl1).trigger('chosen:updated');


来源:https://stackoverflow.com/questions/29656711/why-does-the-asp-net-dropdownlist-does-not-default-to-0-if-chosen-jquery-is-used

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