简体   繁体   中英

How to get the option value in javascript

i have this code:

<SELECT onChange="chData(this,this.value)">
<OPTION VALUE="_MIPS-LRSYSCPU">MIPS
<OPTION VALUE="_XXCEC-LRSYSCPU">% CEC
<OPTION VALUE="_nIFL-LRSYSCPU">nIFL
</SELECT>

and I need to take with javascript all the value (not the text) of the option value that I have in the HTML PAGE. The problem is that In know that the value contains the word "-LRSYSCPU", but I don't know the previous part (Example _MIPS). the second problem is that I don't have the ID in the select so how can I take the option value? I have seen that people use this code:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

but I don't have the id so i dont know how to proceed..

I need to create an array with this three values : _MIPS-LRSYSCPU, _XXCEC-LRSYSCPU and _nIFL-LRSYSCPU. Thanks

If you are using only single select on the whole page then you can use -

let selectTags = document.getElementsByTagName('select');

then it will return you array of HTMLCollection [select]. Now you can get your select using selectTags[0], which is an object of type HTMLCollection . This object contains childNodes . Iterating over child nodes will give you all options and there values.

To grab all the option values in the page that include the substring "LRSYSCPU" you can use this code:

 // Grab all the options in the page const options = document.querySelectorAll('option'); // `filter` out the options that have the "LRSYSCPU" substring // in their values const filtered = [...options].filter(({ value }) => value.includes('-LRSYSCPU')); // Iterate over those filtered options with `map` and return only // the values const values = filtered.map(({ value }) => value); console.log(values); 
 <select> <option value="temp">temp</option> <option value="_MIPS-LRSYSCPU">MIPS</option> <option value="_XXCEC-LRSYSCPU">% CEC</option> <option value="temp2">temp2</option> <option value="_nIFL-LRSYSCPU">nIFL</option> </select> 

Documentation

You can use document.querySelectorAll() to find all options that end with -LRSYSCPU . You can then loop over them and test whether they're selected.

let options = document.querySelector("option[value$=-LRSYSCPU]");
for (let i = 0; i < options.length; i++) {
    if (options[i].selected) {
        value = options[i].value;
        text = options[i].text;
        break;
    }
}

If you use jQuery, it has a selector extension :selected , so you can do this without a loop:

var option = $("option[value$=-LRSYSCPU]:selected");
var value = option.val();
var text = option.text();

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