xploreraj
xploreraj

Reputation: 4362

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.

Upvotes: 1

Views: 111

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281942

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

Upvotes: 3

palaѕн
palaѕн

Reputation: 73956

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>

Upvotes: 1

Joshua R.
Joshua R.

Reputation: 2302

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

Upvotes: 1

Related Questions