Riya
Riya

Reputation: 425

get value from multiple button clicked in javascript

I am trying to get the value of button according to the click event but it's returning null value. can anyone suggest me proper way to do it ?

code::

<html lang="en">
<head>
  <title>elevator</title>
</head>
<body>
 <button id="btn0" onclick="inFunction(0)" >0</button>
  <button id="btn1" onclick="inFunction(1)" >1</button>
  <button id="btn2" onclick="inFunction(2)" >2</button>
  <button id="btn3" onclick="inFunction(3)" >3</button>
  <button id="btn4" onclick="inFunction(4)" >4</button>
  <button id="btn5" onclick="inFunction(5)" >5</button>

 <script>
 function inFunction(clickedValue) {
      var btnValue = document.getElementById(clickedValue.id).value;
      console.log(btnValue);
}
 </script>

</body>

Upvotes: 0

Views: 3924

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29109

clickedValue in your method is a number, not an object. Send in 'this' or the id. No need to getElementById if you already have the element though.

Also either get the innerText, or set the input='...' attribute if you want it different than what is displayed.

<html lang="en">
<head>
  <title>elevator</title>
</head>
<body>
 <button id="btn0" onclick="inFunction(this)" >0</button>
  <button id="btn1" onclick="inFunction(this)" >1</button>
  <button id="btn2" onclick="inFunction(this)" >2</button>
  <button id="btn3" onclick="inFunction(this)" >3</button>
  <button id="btn4" onclick="inFunction(this)" >4</button>
  <button id="btn5" onclick="inFunction(this)" >5</button>

 <script>
 function inFunction(ele) {
      var btnValue = ele.innerText;
      console.log(btnValue);
}
 </script>

</body>

Upvotes: 2

Related Questions