开发者

how to set the items selected in a listbox with values provided by an array?

开发者 https://www.devze.com 2023-04-12 18:10 出处:网络
In my apsx page, I have a listbox (techGroups) that has some items that are preselected. The user can change the selections. Meanwhile, I have a reset button. When the user click the reset button, the

In my apsx page, I have a listbox (techGroups) that has some items that are preselected. The user can change the selections. Meanwhile, I have a reset button. When the user click the reset button, the listbox will be restored with those preselected items selected, while others are not.

I write following javascript function for the reset button's onclientclick. Somehow, after i click the reset button, only the first preselected item get selected, all other preselected items are not.

reset()
{
       var selectedGroups = hiddenfield1.value.split(","); //i saved those preselected items in a 开发者_如何学编程hiddenfield
        for (var i = 0; i < techGroups.options.length; i++) {
            for (var j = 0; j < selectedGroups.length; j++) {
                if (techGroups.options[i].value == selectedGroups[j]) {
                    techGroups.options[i].selected = true;
                }
            }
        }
}

Can anybody help me to look at my code and tell me what is wrong? Thanks.


jQuery allowed? if so please see it working here (if not, please disconsider):

http://jsfiddle.net/sW8HX/4/


May be reference issue (DOM). Try this,

JavaScript:

<script type="text/javascript">
window.onload = function () {
    var btnReset = document.getElementById("btnReset");
    btnReset.onclick = function () {
        var hid1 = document.getElementById("hiddenField1");
        var techGroups = document.getElementById("techGroups");

        var selectedGroups = hid1.value.split(","); //i saved those preselected items in a hiddenfield

        for (var i = 0; i < techGroups.options.length; i++) {
            for (var j = 0; j < selectedGroups.length; j++) {
                if (techGroups.options[i].value == selectedGroups[j]) {
                    techGroups.options[i].selected = true;
                }
            }
        }
    };
};
</script>

Markup:

<form id="form1" runat="server">
<div>
    <input type="hidden" id="hiddenField1" value="aa,bb,cc" />
    <select id="techGroups" size="4" multiple="multiple">
        <option value="rr">rr</option>
        <option value="aa">aa</option>
        <option value="cc">cc</option>
        <option value="zz">zz</option>
        <option value="bb">bb</option>
        <option value="dd">dd</option>
    </select>
    <input type="button" id="btnReset" value="Reset" />
</div>
</form>
0

精彩评论

暂无评论...
验证码 换一张
取 消