2012-08-03 34 views
3

我有一个视图和一个循环,其中呈现部分视图。通过局部视图,我有一个多选择列表框。所以根据循环中的项目的数量,可以有(n)个列表框。使用jquery查找所选项目的mvc列表框

我的目标是从第一个列表框中获取所有选定的项目,并在列表框的其余部分预先选择它们。我不想追加到剩余的列表框,但只是在第一个选择的内容中,我会选择剩下的列表框。所有的列表框都会有相同的项目。

我面临的困难是从第一个找到选定的索引或项目,然后我会在剩下的部分中进行预选,如果我能够在第一个项目中获得所选项目的索引将会很有帮助。它从所有列表框中提供选定的项目。请帮助:

列表框decleration局部视图中

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

按钮,这使得该功能

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

JS功能:

function broadcast() { 
    //var element = $('select[multiple]'); This gives me access of all listboxes 
    // var firstListBoxSelected = $('select[multiple][1] option:selected').text(); t 
} 

回答

7

在你的榜样,你给你的列表框“lstbox”的ID。你可以用它来寻找“列表框中的”使用jQuery:

var box = $('#lstbox'); // or $('select[multiple]:first') for just the first one 

从那里,你可以修改代码来过滤下降到只有选定的选项:

var selected = $('#lstbox option:selected'); 

最后,得到该指标,我们再次进行更改和添加的代码只是一对夫妇更行:

var selectedIndices = []; // create an empty array 
$.each($('#lstbox option:selected'), function(index, value) { // loop over each option 
    selectedIndices.push(index); // add the index to the array 
}); 

或者稍微不同的方法,以:selected出你选择的,而是手动签克元素是否处于选中状态(可能是在性能方面发好):

var selectedIndices = []; 
$.each($('#lstbox option'), function(index, value) { 
    if (this.selected) { // 'this' is the current DOM element, same as 'value' 
     selectedIndices.push(index); 
    } 
}); 

然后你可以使用selectedIndices预选其余的,但首先我们必须找到他们:

var otherBoxes = $('select[multiple]:not(:first)'); // not the first one 
// or 
var otherBoxes = $('select[multiple]:gt(0)'); // greater than the 0th one 

,然后改变自己的选择的选项:

var numSelected = selectedIndices.length; 
$.each(otherBoxes, function() { 
    for (int i = 0; i < numSelected; i++) { 
     this.options[selectedIndices[i]].selected = true; 
    } 
}); 

编辑:Working jsFiddle example

我的jsfiddle的解决方案看起来像这样(我结合循环,所以你只需要一次迭代选择元素):

$(function() { 
    var selectedIndices = []; 
    $.each($('select[multiple]'), function(sIndex, sValue) { 
     if (sIndex == 0) { 
      $.each(this.options, function (oIndex, oValue) { 
       if (this.selected) 
        selectedIndices.push(oIndex); 
      }); 
     } else { 
      for (var i = 0; i < selectedIndices.length; i++) { 
       this.options[selectedIndices[i]].selected = true; 
      }  
     } 
    }); 
}); 
+0

写得很好的答案! – Gromer 2012-08-03 22:06:11

+0

@Cory哇这个伟大的!我用你的第二种方法组合成一个循环。谢谢!! – user721 2012-08-04 00:21:43

相关问题