我有(n)个列表箱。我有一个执行函数的按钮,在该函数中,我试图获取第一个列表框中选定的项,以及在第一个列表框中选择的任何索引/项,我将在其余的列表框中选择相同的选项。所有列表框都有完全相同的列表项。
ListBox:
@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");
// }
}
}
发布于 2012-08-02 11:05:57
试着做这样的事情:
@{
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>
如果再次获取一些随机列表,则可以使用调试器检查并看到值已更改。
我对网络编程还很陌生,所以这看起来很难看,但是它应该给你一个如何完成你的任务的想法。
https://stackoverflow.com/questions/11782743
复制相似问题