lomine
lomine

Reputation: 1181

React - how to display data value in select menu

I have a demo here

Its a simple react app where I'm creating a select menu from data in an array

The select menu has a value attribute and a data-number attribute.

When the select menu changes I want to display the value and data-number.

I can't display the data-number using dataset

setNumber(e.currentTarget.dataset.number);

How can I output the data-number value

Upvotes: 0

Views: 513

Answers (5)

Arvind Pal
Arvind Pal

Reputation: 521

You can use the event.target[event.target.selectedIndex].getAttribute("data-number")) to get the data-number attribute value of selected option.

I also tried in you demo code , it is working fine

const handleChange = e => {
        console.log('value = ', e.target.value);
        console.log('number = ', e.target[e.target.selectedIndex].getAttribute("data-number"));  
        setValue(e.currentTarget.value);
        setNumber(e.target[e.target.selectedIndex].getAttribute("data-number"));
      };

Upvotes: 0

Anish Antony
Anish Antony

Reputation: 1525

You can use the below code.

  const onChange =(e) => {
  const selectElement = e.currentTarget;
  const selectedOption = selectElement.childNodes[selectElement.selectedIndex]
  const selectedNumber =  selectedOption.getAttribute('data-number');
  setNumber(selectedNumber)
}

Upvotes: 0

Chuck
Chuck

Reputation: 804

You can change as follow.

const handleChange = e => {
    ...
    console.log('number = ', e.target.selectedOptions[0].dataset.number);
    setNumber(e.target.selectedOptions[0].dataset.number);
    ...

Upvotes: 0

Javvy7
Javvy7

Reputation: 146

This somewhat might seem long but you can access <option> element using - e.target.options[e.target.selectedIndex].dataset.number. This will return the value of your data attribute.

Where e.target.selectedIndex is the index of the selected option. https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex

Upvotes: 0

Abhijit Sil
Abhijit Sil

Reputation: 191

You can collect the number from the datas array depending on the value you collected by e.target.value.

const handleChange = e => {
   console.log('value = ', e.target.value);
   console.log(datas.find( data => data.value === e.target.value).number);
   setValue(e.currentTarget.value);
   setNumber(datas.find( data => data.value === e.target.value).number);
};

Upvotes: 1

Related Questions