-2

I have got 3 buttons and need to change their text when it's clicked using Javascript. It works fine for the first one but the rest of them doesn't get updated. I know one way of achieving this is by adding JS for different inputs and id. But I just want to write a single function which solves this issue.

<input id=-btn" type="button" value="ADD" />

<input id="btn" type="button" value="ADD" />

<input id="btn" type="button" value="ADD" />


document.getElementById("btn").addEventListener(
        "click",
        function (event) {
          if (event.target.value === "ADD") {
            event.target.value = "ADDED";
          } else {
            event.target.value = "ADD";
          }
        },
        false
      );
Sam
  • 111
  • 1
  • 9
  • Does this answer your question? [JavaScript and getElementById for multiple elements with the same ID](https://stackoverflow.com/questions/3607291/javascript-and-getelementbyid-for-multiple-elements-with-the-same-id) – Nick Jun 11 '22 at 08:24

2 Answers2

1
<input id=-btn" type="button" value="ADD" onclick="func(this)"/>

<input id="btn" type="button" value="ADD"  onclick="func(this)"/>

<input id="btn" type="button" value="ADD" onclick="func(this)"/>


<script>
        function func(event) {
          if (event.value === "ADD") {
            event.value = "ADDED";
          } else {
            event.value = "ADD";
          }
        }
      </script>
L3xpert
  • 1,109
  • 1
  • 10
  • 19
0

function changeValue(event) {
      if (event.target.value === "ADD") {
        event.target.value = "ADDED";
      } else {
        event.target.value = "ADD";
      }
    }
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>
</head>

<body>

  </head>

  <body>

    <input id="btn" onclick="changeValue(event)" type="button" value="ADD" />

    <input id="btn" onclick="changeValue(event)" type="button" value="ADD" />

    <input id="btn" onclick="changeValue(event)" type="button" value="ADD" />
  </body>



</body>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

</html>