简体   繁体   English

如何转让 <option>标签的元素放入javascript数组中?

[英]How to transfer an <option> tag's element into an array in javascript?

How should I get all the options inside a dropdown list (under html) and convert it into an array in Javasctipt? 我应该如何在下拉列表(在html下)中获取所有选项,并将其转换为Javasctipt中的数组? The code snippet comes from a jsp/ html. 该代码段来自jsp / html。 The Form.projectList is Java object call Form.projectList是Java对象调用

<c:forEach items="${Form.projectList}" var="val">
   <option ${Form.project eq val.projectId?'selected="selected"':''} 
           value="<c:out value="${val.projectId}"/>"><c:out value="${val.project}"/></option>
</c:forEach>

You need the name of your select element and access the options collection off of it. 您需要select元素的名称,然后访问其options集。 For example, if you had a form named myForm and a select element called myItems then you would access the list of options in that drop down like this: 例如,如果您有一个名为myFormform和一个名为myItemsselect元素,那么您将访问该下拉列表中的选项列表,如下所示:

for(var i = 0; i < document.myForm.myItems.options.length; i++)
{
   alert(document.myForm.myItems.options[i].value);
}

Use the id of the select and jquery to populate an array. 使用select和jquery的ID填充数组。 Like the following 像下面

var arr=new Array();
$("#dropdwonid option").each(function()
{
    arr.push($(this).text());
});

Just create a JS array like you usually would. 只需像通常那样创建一个JS数组即可。 Then push the values in by placing the array in you JSP loop. 然后通过将数组放入JSP循环中来推入值。

<script language="javascript">
var myJsArry = [];  // JS array
// Your JSP loop

<c:forEach items="${Form.projectList}" var="val">

    myJsArry.push(${val.projectId);  // fill your JS array

    <option ${Form.project eq val.projectId?'selected="selected"':''} 
        value="<c:out value="${val.projectId}"/>"><c:out value="${val.project}"/>
    </option>
</c:forEach>
</script>

Populate JavaScript Array from JSP List 从JSP列表填充JavaScript数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM