Search code examples
javascripthtmlonkeyup

Display results of onkeyup event on multiple id


I am trying to get the text in a multiple text box as the user types in it (jsfiddle playground):

function Input1(a) {
  document.getElementById("Input11").innerHTML = a.value;
  document.getElementById("Input12").innerHTML = a.value;
  document.getElementById("Input13").innerHTML = a.value;
}
function Input2(b) {
  document.getElementById("Input21").innerHTML = b.value;
  document.getElementById("Input22").innerHTML = b.value;
  document.getElementById("Input23").innerHTML = b.value;
}

And Result as

<span id="text-box">
 <input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
  </span><br><br>
  <span id="Input11">Input11</span><br>
  <span id="Input12">Input12</span><br>
  <span id="Input13">Input13</span><br><br>
<span id="text-box">
  <input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span id="Input21">Input21</span><br>
<span id="Input22">Input22</span><br>
<span id="Input23">Input23</span><br><br>

The above code is working fine.

But I want to Display each "onkeyup" input multiple times on-page. So here I need to update the function and span id (As if I use the same id then it will not display anything after 2nd call)

Please help me to reformat the above JavaScript and HTML so Just Define function for input and display it on all HTML span id without changing span id each time...


Solution

  • you can use class instead of id and use querySelectorAll to select all elements here is sample code

    function Input1(a) {
          const elements = document.querySelectorAll(".Input1");
          elements.forEach((e)=>{
            e.innerHTML = a.value;
          })
          
        }
     function Input2(b) {
          const elements = document.querySelectorAll(".Input2");
           elements.forEach((e)=>{
            e.innerHTML = b.value;
          })
        }
        <html>
        <body><span id="text-box">
            <input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
          </span><br><br>
          <span class="Input1">Input11</span><br>
          <span class="Input1">Input12</span><br>
          <span class="Input1">Input13</span><br><br>
        <span id="text-box">
          <input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
        </span><br><br>
        <span class="Input2">Input21</span><br>
        <span class="Input2">Input22</span><br>
        <span class="Input2">Input23</span><br><br>
        </body>
     </html>