使用Javascript来选择多个选项 [英] Javascript to Select Multiple options
问题描述
我有一个允许多个选项的选择框。用户保存这些选项后,将它们存储在数据库表中。
然后我可以读取这个数据库表以获得他们再次选择的选项。我需要能够从数据库中获取这些数据,并将其放入一个数组中,然后让这些选择框中的选项在他们选择编辑选项时被预选。
将数据读入数组很好,我知道如何在选择框中选择一个选项,但是我不确定如何处理在javascript中选择的多个选项。
有人可以帮我弄清楚这样做所需的JavaScript吗?
纯JavaScript解决方案
< select id =choicemultiple =multiple>
< option value =1>一个< / option>
< option value =2> two< / option>
< option value =3> three< / option>
< / select>
< script type =text / javascript>
var optionsToSelect = ['One','three'];
var select = document.getElementById('choice');
for(var i = 0,l = select.options.length,o; i< l; i ++)
{
o = select.options [i];
if(optionsToSelect.indexOf(o.text)!= -1)
{
o.selected = true;
}
}
< / script>
虽然我同意这应该在服务器端完成。
I have a form with a select box that allows multiple options. After a user saves these options, it stores them in a database table.
I can then read this database table to get the options they chose one again. I need to be able to grab this data from the database, put it into an array, then have the options in that select box to be pre-selected when they go to "Edit" their options.
Reading the data into an array is fine, and I know how to make a single option selected within a select box, however I'm not sure how to handle multiple options being selected in javascript.
Can someone help me figure out the javascript required to do this?
A pure javascript solution
<select id="choice" multiple="multiple">
<option value="1">One</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<script type="text/javascript">
var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );
for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
o = select.options[i];
if ( optionsToSelect.indexOf( o.text ) != -1 )
{
o.selected = true;
}
}
</script>
Although I agree this should be done server-side.
这篇关于使用Javascript来选择多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!