MVC 3在多个列表框中,如何使用jquery传输列表框项

时间:2012-08-02 17:29:54

标签: jquery asp.net-mvc-3

我有(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");
//      }

    }
}

1 个答案:

答案 0 :(得分: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>  

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

我自己仍然是网络编程的新手,所以这可能看起来很难看,但它应该让你知道如何完成你的任务。