如何将数组从HTML传递给Javascript? [英] How to pass an array from HTML to Javascript?
问题描述
我的表单中有多个< select>
下拉框。我希望将这些下拉框中的值作为数组传递给JavaScript函数。
I have a form which has multiple <select>
drop-down boxes. I wish to pass the value in these drop-down boxes as an array to a JavaScript function.
目前我的代码如下:
<select name="findByMaterial" onChange="filterFilms('Material',this.value)">
{% for film in all_films %}
<option value="{{film.f_material}}">{{film.f_material}}</option>
{% endfor %}
</select>
其中all_films是来自Django框架的变量(很可能你不需要关心它)。
Where all_films is a variable from Django framework (Most probably you need not concern yourself with it).
我想做的是即使我有多个不同名称的选择,例如 findByMaterial
和 findByColor
,我更改了 findByColor
,然后它应该调用 filterFilms(String,Value)
JS函数。
What I want to do is that even if I have multiple selects with different names such as findByMaterial
and findByColor
, and I change the findByColor
, then it should call the filterFilms(String,Value)
JS function.
任何正确方向的指针都会受到很多赞赏。
Any pointers in the right direction would be appreciated a lot.
PS:这个问题可能类似于如何将数组值从html onchange action传递给JavaScript函数?,但绝对不是我想要的。
PS: This question is probably similar to how to pass array values to JavaScript function from html onchange action?, but it is definitely not what I am looking for.
CLarification:
我想创建一个过滤器。因此,我希望能够访问 color
的属性以及材料
。
推荐答案
在线演示: http:// jsfiddle.net/thefourtheye/jRym8/
<html lang = "en">
<head>
<title> Document </title>
<script>
function filterFilms(selectBox) {
var displayArea = document.getElementById("displayArea");
displayArea.innerHTML = selectBox.id + "," + selectBox.value + "," + selectBox.selectedIndex + "," +
selectBox.options[selectBox.selectedIndex].text;
}
</script>
</head>
<body>
<select onchange="filterFilms(this);" id="films">
<option value="film1">Film Text 1</option>
<option value="film2">Film Text 2</option>
<option value="film3">Film Text 3</option>
</select>
<select onchange="filterFilms(this);" id="colors">
<option value="color1">Color 1</option>
<option value="color2">Color 2</option>
<option value="color3">Color 3</option>
</select>
<div id="displayArea"/>
</body>
</html>
您可以使用相同的功能执行此操作。将当前元素作为参数传递。并且
You can use the same function to do this. Pass the current element as the parameter. And
- 您可以获取用
selectBox.id
点击的选择框的ID - 您可以使用
selectBox.value获取所选选项的值
- 您可以获得选择选项的索引与
selectBox.selectedIndex
- 您可以使用
selectBox.options [selectBox]获取所选选项的文本.selectedIndex] .text
- You can get the id of the select box clicked with
selectBox.id
- You can get the selected option's value with
selectBox.value
- You can get the selected option's index with
selectBox.selectedIndex
- You can get the selected option's text with
selectBox.options[selectBox.selectedIndex].text
这篇关于如何将数组从HTML传递给Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!