[SOLVED] increment in the function name and id javascript

Issue

I have number of input types and buttons….every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop….where loop will increase in the function name and id……

    <input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
    <input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
    <input type="number" id="s3"> <button onclick="increment_s3">Add</button>

here is JavaSc code

<script>
  var i = 1;
  for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data; 
function ['increment_'+i]() {
    data = data + 1;
    document.getElementById("s"+i).placeholder = data;
     i++;
}
  }
</script>

Solution

You can’t program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.

After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.

Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn’t count as the form value.

// This is for handling onclick 
function increment(id) {
    var elem = document.getElementById(id);
    elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
  var data = 0;
  document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>

What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.

// This is for handling onclick 
function increment(id) {
    var elem = document.getElementById(id);
    elem.value = parseInt(elem.value) + 1;
}

var divElem = document.querySelector('div');

// Set up empty first
divElem.innerHTML = "";

for(var i=1; i<=5; i++) {
  // Create elements here
  var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
  
  // Push them all into innerHTML
  divElem.innerHTML += innerElem;
}
<div></div>

You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.

Answered By – Dhana D.

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.