0

I would like to keep count every time the user clicks a the add row button. Here's the code I have that's not working.

function add_more_row() {
  var rows_count = ParseInt(document.getElementById("rows_count").value);
  rows_count += 1;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />

What am I doing wrong?

2
  • 1
    Just so you know, the statement that you've read previous/related questions isn't helpful if you don't link to what questions you're referring to and describe why they didn't help. Commented Nov 10, 2016 at 2:24
  • What is being displayed in the console? Commented Nov 10, 2016 at 5:11

3 Answers 3

2

Your code only gets the value and increases it, does not assign the value to the input field. Add this line after the increment statement:

document.getElementById("rows_count").value = rows_count;

Also it's parseInt() with lowercase p not ParseInt().

function add_more_row() {
  var inputRow = document.getElementById("rows_count"),
      rows_count = parseInt(inputRow.value);
  rows_count += 1;
  inputRow.value = rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />

Sign up to request clarification or add additional context in comments.

1 Comment

Retrieving the element from the DOM twice is sloppy.
1

function add_more_row() {
  var rows_count = parseInt(document.getElementById("rows_count").value);
  rows_count += 1;
  document.getElementById("rows_count").value= rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />

Comments

0

It is because you declare the variable inside the function. So, the variable does not increase.

 var rows_count=ParseInt(document.getElementById("rows_count").value);
 function add_more_row()
 {
   rows_count += 1;
 }

2 Comments

Nope, I only need that variable inside the function scope. Thank you though.
Unfortunately, this won't work. And you haven't fixed the typo with ParseInt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.