使用 Javascript 在多选中设置选定的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8344522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Selected Indices in Multi Select Using Javascript
提问by CatchingMonkey
Im not sure why this isnt working and would love some help with it! And yes i have looked at this
我不知道为什么这不起作用,并且希望得到一些帮助!是的,我看过这个
Im trying to set multiple options in a select element as selected using an array holding the values i want selected and interating through both the array and the options in the select element. Please find code below:
我试图在选择元素中设置多个选项,使用一个数组保存我想要选择的值并通过数组和选择元素中的选项进行交互。请在下面找到代码:
// value is the array.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].text == value[j]) {
el[i].selected = true;
alert("option should be selected");
}
}
}
After completing these loops nothing is selected, even though the alert() fires.
完成这些循环后,即使 alert() 触发,也不会选择任何内容。
Any ideas are welcome!
欢迎任何想法!
Thanks
谢谢
CM
厘米
PS (not sure whats happened to the code formatting).
PS(不确定代码格式发生了什么)。
EDIT: Full function
编辑:全功能
if (CheckVariableIsArray(value) == true) {
if (value.length > 1) { // Multiple selections are made, not just a sinle one.
var checkBoxEl = document.getElementById(cbxElement);
checkBoxEl.checked = "checked";
checkBoxEl.onchange(); // Call function to change element to a multi select
document.getElementById(element).onchange(); // Repopulates elements with a new option list.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].text === value[j]) {
el[i].selected = true;
i = el.length + 1;
}
}
}
//document.getElementById(element).onchange();
}
}
else {
for (var i = 0; i < el.length; i++) {
if (el[i].innerHTML == value) {
el.selectedIndex = i;
document.getElementById(element).onchange();
}
}
}
回答by simshaun
Works for me. Are you setting el and value correctly? And are you sure you want to look at each option's innerHTML instead of it's value attribute?
对我来说有效。您是否正确设置了 el 和 value?您确定要查看每个选项的 innerHTML 而不是它的 value 属性吗?
See the jsFiddle.
请参阅jsFiddle。
HTML:
HTML:
<select id="pick_me" multiple="multiple">
<option>Hello</option>
<option>Hello</option>
<option>Foo</option>
<option>Bar</option>
</select>
JS:
JS:
var value = ['Foo', 'Bar'],
el = document.getElementById("pick_me");
// value is the array.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].innerHTML == value[j]) {
el[i].selected = true;
//alert("option should be selected");
}
}
}
回答by u1299702
Well, first of all, you must set the html select control multiple property, something like this "<select multiple="multiple">...</select>", and then you can use the javascript function SetMultiSelect (defined as below) to set the select html control:
嗯,首先你必须设置html select控件的multiple属性,像这样“<select multiple="multiple">...</select>”,然后你就可以使用javascript函数SetMultiSelect(定义如下) 设置选择 html 控件:
function SetMultiSelect(multiSltCtrl, values)
{
//here, the 1th param multiSltCtrl is a html select control or its jquery object, and the 2th param values is an array
var $sltObj = $(multiSltCtrl) || multiSltCtrl;
var opts = $sltObj[0].options; //
for (var i = 0; i < opts.length; i++)
{
opts[i].selected = false;//don't miss this sentence
for (var j = 0; j < values.length; j++)
{
if (opts[i].value == values[j])
{
opts[i].selected = true;
break;
}
}
}
$sltObj.multiselect("refresh");//don't forget to refresh!
}
$(document).ready(function(){
SetMultiSelect($sltCourse,[0,1,2,3]);
});
回答by Sean
Ran into this question and wasn't satisfied with the answers.
Here's a generic, non-jQuery version. It utilises Array.indexOf
where possible, but falls back to a foreach loop if it isn't available.
遇到这个问题,对答案不满意。这是一个通用的非 jQuery 版本。它Array.indexOf
在可能的情况下使用,但如果不可用则回退到 foreach 循环。
Pass a node into the function, alongside an array of values. Will throw an exception if an invalid element is passed into it. This uses ===
to check against the value. For the most part, make sure you're comparing the option's value to an array of strings.
将一个节点和一组值一起传递到函数中。如果传入无效元素,则会抛出异常。这用于===
检查值。大多数情况下,请确保将选项的值与字符串数组进行比较。
E.g. selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );
例如 selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );
var selectValues = (function() {
var inArray = ( function() {
var returnFn;
if( typeof Array.prototype.indexOf === "function" ) {
returnFn = function(option, values) {
return values.indexOf( option.value ) !== -1;
};
} else {
returnFn = function(option, values) {
var i;
for( i = 0; i < values.length; i += 1 ) {
if( values[ i ] === option.value ) {
return true;
}
}
return false;
}
}
return returnFn;
}() );
return function selectValues(elem, values) {
var
i,
option;
if( typeof elem !== "object" || typeof elem.nodeType === "undefined" )
throw 'selectValues() expects a DOM Node as it\'s first parameter, ' + ( typeof elem ) + ' given.';
if( typeof elem.options === "undefined" )
throw 'selectValues() expects a <select> node with options as it\'s first parameter.';
for( i = 0; i < elem.options.length; i += 1 ) {
option = elem.options[ i ];
option.selected = inArray( option, values );
}
}
}());