Reputation: 33
How can I get option value. I want to change the name="<value>"
based on selected option value.
So that I can send name value to the spring controller along with onChange=""
.
I want to change select name="report/leavereport/weeklysummery"
based on option selected value.
<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,
Upvotes: 3
Views: 3945
Reputation: 29521
Here is one possible (unobtrusive) solution using getAttribute
and 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
.
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>
Upvotes: 0
Reputation:
Set a id to the select
.
<select id="select"...>...</select>
Then set the onchange
event of the select
element. 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. I'd not use querySelector
because older browsers may not support it.
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;
};
Upvotes: 0
Reputation: 1075855
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.
Upvotes: 2