Aditya
Aditya

Reputation: 431

Increment of counter on dynamic addition of rows

I'm trying to add the rows dynamically plus auto-increment of a counter.I want to start with 1 then 2 then 3 and so on . I have added my code on plunker ,in which every time the max value is getting in first column like 4 then 1,1,2,3.Where am i going wrong ?i Want it to be 1,2,3,4.

Here is the plunker link http://plnkr.co/edit/GuDbJ3SHOPvWkHfNfd8E?p=preview

            var _counter = 0;           
        function Add() {
            _counter++;
            var oClone = document.getElementById("template").cloneNode(true);
            oClone.id += (_counter + "");
            document.getElementById("placeholder1").appendChild(oClone);
            document.getElementById("myVal").value=_counter;

        }

    <div id="placeholder1">
    <div id="template">
        <div>
        Value:<input type="text" id="myVal" placeholder="1">
        Quantity:<input type="text" placeholder="Qty">

            <input type="button" onClick="Add()" value="Click! ">
        </div>
    </div>

Upvotes: 1

Views: 379

Answers (2)

rhopper
rhopper

Reputation: 49

I think it is because you have multiple divs with the id="myVal". The id attribute should be unique on the page. If not, your page will still load, but you may have unexpected behavior.

You are changing the id of the template div, but not the myVal div.

Upvotes: 2

Matt Burland
Matt Burland

Reputation: 45135

I assume you are looking for something like this:

var _counter = 0;

function Add() {
  _counter++;
  var oClone = document.getElementById("template").cloneNode(true);
  oClone.id += (_counter + "");
  document.getElementById("placeholder1").appendChild(oClone);
  oClone.getElementsByClassName("myVal")[0].value = _counter;
}
<div id="placeholder1">
  <div id="template">
    <div>
      Value:
      <input type="text" class="myVal" placeholder="1">Quantity:
      <input type="text" placeholder="Qty">

      <input type="button" onClick="Add()" value="Click! ">
    </div>
  </div>
</div>

In your original you are cloning your template with the same id for the input. So when you do document.getElementById("myVal").value=_counter;, you only get the first input. I changed it to use class instead and get the input with the appropriate class that is a child of the cloned node.

Upvotes: 1

Related Questions