简体   繁体   中英

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. 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,

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.

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;

};

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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