0

我有(n)个列表框。我有一个执行函数的按钮,在该函数中,我试图获取第一个列表框的选定项目以及在第一个列表框中选择的任何索引/项目,我将在剩余的列表框中选择相同的选项。所有列表框都有完全相同的列表项。

列表框:

@Html.ListBoxFor(model => model.ServiceTypes, new MultiSelectList(RunLog.Domain.Lists.GlobalList.PartsServiceTypes(), "ID", "Name"), new { style = "width: 200px; height: 80px;", id = "lstbox_@(model.PartID)" })

按钮:

@*<input id="button" type="button" class="art" onclick="dosomething()" name="broadcast" value="+" />*@

JS功能:

function dosomething() {

    //The following line returns all the listboxes
    var listBoxes =  var listBoxes = $('select[multiple]');

    //In the following line I am trying to access the items from the first listbox but not sure how to access it, would it be by index. it does not work
    var x = $('listBoxes[1] option:selected')

    //In the following loop I would iterate through the selected items from the first listbox and select them in the rest of the listboxes
    for (var i = 0; i < listBoxes.length; i++) {
        var element = listBoxes[i];

//      if (element.multiple) {
//          alert("im a multilistbox");
//      }

    }
}
4

1 回答 1

0

尝试这样的事情:

@{
var list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
}

@Html.ListBox("listbox", new SelectList(list), new { id = "listbox", multiple = "multiple" })

<input type="button" value="Click me!" onclick="GetSelected()" />

<script type="text/javascript">
    function GetSelected() {
        var listboxitems = document.getElementById("listbox");

        for (var i = 0; i < listboxitems.length; i++) {
            if (listboxitems[i].selected) {
                alert(listboxitems[i].textContent);
            }
        }
    }
</script>

您可以像这样保存列表项的文本内容,显然:

var element = listboxitems[i].textContent;  

更新:
针对您的评论,请尝试以下示例:

@{
    var list = new List<string>();
    list.Add("one");
    list.Add("two");
    list.Add("three");

    int i;

    for(i = 0; i < 5; i++)
    {
        @Html.ListBox("listbox"+i, new SelectList(list), new { id = "listbox" + i, multiple = "multiple" })
    }
}

<input type="button" value="Click me!" onclick="GetSelected()" />

<script type="text/javascript">
function GetSelected() {
    var index = @i;

    var firstListBoxItems = document.getElementById("listbox0");

    for (n = 1; n < index; n++) {
        var currentListBoxItems = document.getElementById("listbox"+n);

        for (var i = 0; i < firstListBoxItems.length; i++) {
            if (firstListBoxItems[i].selected) {
                currentListBoxItems[i].value = "NewValue"+i;
            }
        }
    }
}
</script>  

如果您再次获取一些随机列表,则可以使用调试器检查并查看值已更改。

我自己还是网络编程新手,所以这可能看起来很难看,但它应该让您了解如何完成您的任务。

于 2012-08-02T19:05:57.547 回答