[英]How to change HTML select name based on option value
How can I get option value. 我怎样才能获得期权价值。 I want to change the
name="<value>"
based on selected option value. 我想根据选定的选项值更改
name="<value>"
。 So that I can send name value to the spring controller along with onChange=""
. 这样我就可以将名称值与
onChange=""
一起发送给spring控制器。
I want to change select name="report/leavereport/weeklysummery"
based on option selected value. 我想根据选项选择值更改
select name="report/leavereport/weeklysummery"
。
<select name="" onChange="document.getReportAll.submit()">
<option value="">Select Report Type</option>
<option value="report">TIME REPORT</option>
<option value="leavereport">LEAVE REPORT</option>
<option value="weeklysummery">TIME SUMMARY</option>
</select>
Thank you, 谢谢,
The shortest change, given that code and modern browsers, would be: 鉴于代码和现代浏览器,最短的变化是:
onChange="this.name = this.value; document.getReportAll.submit()"
...since within the attribute event handler, this
refers to the select element and modern browsers reflect the option value as value
in single-selects. ......因为属性事件处理程序中,
this
指的是选择元素和现代的浏览器反映期权价值为value
单选择。
Set a id to the select
. 将id设置为
select
。
<select id="select"...>...</select>
Then set the onchange
event of the select
element. 然后设置
select
元素的onchange
事件。 It fires when a option is selected. 选择一个选项时会触发它。
If the selector value
is undefined, then the browser doesn't support it, so it's possible to get the selected element iterating the options and checking if the attribute selected
is included. 如果选择器
value
未定义,则浏览器不支持它,因此可以使所选元素迭代选项并检查是否包含selected
属性。 I'd not use querySelector
because older browsers may not support it. 我不使用
querySelector
因为较旧的浏览器可能不支持它。
var selector = document.getElementById('select');
selector.onchange = function() {
var value = this.value;
if(!value) {
for(var i = 0, op; op = selector.children[i]; i ++) {
// Check if the attribute selected is valid
if(op.getAttribute('selected')) {
value = op.value;
break;
}
}
}
this.name = value;
};
Here is one possible (unobtrusive) solution using getAttribute
and setAttribute
. 这是一个使用
getAttribute
和setAttribute
可能(不显眼)解决方案。
The script listens for a click on any of the options
and then updates the value of the name
attribute of select
, based on the value of the value
attribute of the option
. 该脚本监听任何的点击
options
,然后更新的值name
的属性select
的基础上,价值value
的属性option
。
var options = document.getElementsByTagName('option'); function changeName() { var value = this.getAttribute('value'); window.alert('name = "' + value + '"'); this.parentNode.setAttribute('name',value); } for (var i = 0; i < options.length; i++) { options[i].addEventListener('click',changeName,false); }
<select name=""> <option value="">Select Report Type</option> <option value="report">TIME REPORT</option> <option value="leavereport">LEAVE REPORT</option> <option value="weeklysummary">TIME SUMMARY</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.