简体   繁体   中英

How to access the selected option in React

In React JSX, I wrote below component:

<select //...
  onChange={event => {alert(event.target); //setState}}
>
    <option id=1>one</option>
    <option id=2>two</option>
</select>

The alert gives me select element. How can I access selected option without jQuery? I am trying to setState on the id, and do corresponding searches and other things.

Instead of an id on select option, provide the value attribute you can then access it as event.target.value .

<select 
    onChange={event => {
        alert(event.target.value);
    }
}>
    <option value="1"> one</option>
    <option value="2"> two</option>
</select>

CodeSandbox

You wouldn't typically access the value directly through the event target. Either bind the control value to component state or store a reference on the parent component... then you can access the value when the event is fired.

See: https://stackoverflow.com/a/47842562/1306026

You can access selected option like:

var elm = event.target;
console.log(elm.options[elm.selectedIndex]);

and then access its value or text like:

console.log(elm.options[elm.selectedIndex].value) 

DEMO ( change the option to see result ):

 function setState() { var elm = event.target; console.log(elm.options[elm.selectedIndex]); console.log(elm.options[elm.selectedIndex].value); } 
 <select onChange="setState()"> <option id=1>one</option> <option id=2>two</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