How to set ASP.net dropdownlist index to 0 from the front-end

五迷三道 提交于 2019-12-02 14:03:53

There are many ways to do this but here is the solution with JavaScript:

function setSelectedIndex(dropdownlist, selVal)
    var ddl1 = document.getElementById(dropdownlist);
    //alert(ddl1.selectedIndex); //displays the proper index...
    if(ddl1.length >= selVal)
    {
       ddl1.selectedIndex = selVal;
    }
}

Call the above function as per you required as below:

setSelectedIndex('<%=ddl1.ClientID %>', 2);

UPDATE As you said you have already set ClientIDMode, try the following updated function:

function setSelectedIndex(selVal){
    var ddl1 = document.getElementById('ddl1');
    if(ddl1.length >= selVal)
    {
       ddl1.selectedIndex = selVal;
    }
}

and call it as:

setSelectedIndex(0);

I was using the Chosen Jquery which caused 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.

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