[英]multiple select boxes - getting values into an array
I have a select box that the options are populated from ajax. 我有一个选择框,这些选项是从ajax填充的。 I also have a button that when clicked clones the select box.
我还有一个按钮,单击该按钮可克隆选择框。
<select name="subcat[0]" id="subcat">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<button name="addmore">Add More</button>
when I click add more it will clone the subcat and increment it so the name is subcat[1], etc... 当我单击添加更多时,它将克隆subcat并将其递增,因此名称为subcat [1],依此类推...
I need to be able to capture all the values of each select and put them in a single array. 我需要能够捕获每个选择的所有值并将它们放在单个数组中。 my problem is that even if the user changes again his select option it still keeps the last value selected as well.
我的问题是,即使用户再次更改了他的选择选项,它仍然会保留最后选择的值。
var elem = document.getElementById('subcat')
var points = [];
for(var i=0,len=elem.length;i<len;i++){
if (elem[i].selected){
points.push(elem[i].value);
}
}
how can I remove the last option selected if the user just changed the same select? 如果用户刚刚更改了相同的选择,如何删除最后选择的选项?
You can store the last selected and can splice it from the array, if I recall correctly you can splice if like this ( supposing that x
has last value ): 您可以存储最后选择的内容并可以从数组中进行拼接,如果我没记错的话,您可以进行如下拼接( 假设
x
具有最后一个值 ):
if(x==elem[i].selected){
elem[i].splice(i,1); //cuts one index in the array where x occurs
]
var elem = document.getElementById('subcat')
var points = [];
for(var i=0,len=elem.length;i<len;i++){
if (elem[i].selected){
if(points[points.length-1] == elem[i].value){
points.pop();
}
points.push(elem[i].value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.