0

I want to get the value of that particurlar label but in the console i'm only getting the event.target.id but not the event.target.value is showing undefined

enter image description here

 async function initiateChat(event) {
  console.log(event.target.id)
  console.log(event.target.value)
 }

<div><label value={customer} id="customer" onClick={initiateChat}>{customer}</label>
likle
  • 1,717
  • 8
  • 10
sonam
  • 105
  • 8
  • Does this answer your question? [Having an issue with e.target.value returning Undefined in React](https://stackoverflow.com/questions/40439316/having-an-issue-with-e-target-value-returning-undefined-in-react) – ggorlen Jun 25 '22 at 20:55

2 Answers2

2

If you really need a click handler on a label and you need the text content of that label, you can use e.target.textCotent.

const label = document.querySelector("#my-label")
label.addEventListener("click", e => {
  console.log(e.target.textContent);
})
<label id="my-label">Hello</label>

That being said, it's not typical or expected for labels to have click handlers, and this won't be accessible. I might recommend changing this to a button if you intend to have some action taken when it's clicked.

Nick
  • 16,066
  • 3
  • 16
  • 32
1

<label>'s can't have values, either use a <button> instead

<div><button value={customer} id="customer" onClick={initiateChat}>{customer}</button>

or use a custom attribute.

<div><label data-value={customer} id="customer" onClick={initiateChat}>{customer}</label>

with the JS:

 async function initiateChat(event) {
  console.log(event.target.id)
  console.log(event.target.getAttribute('data-value'))
 }

I would recommend using a button though.

likle
  • 1,717
  • 8
  • 10