0

I have a function where my button adds a table row every time you click it. My target is, how can I display the value of my button click in my input type="number"? The value of my input type should be starting at "1", and every time when the button is clicked, increment by 1. Thank you in advance.

HTML:

 <button type="button" id="clickCount" onClick="clickMe" value="click me"></button>
 <input type="number" id="showMe" value="1"> // the value of my button clicks should be displayed here
1
  • HTML values are Strings. Cast like (+Element.value), before adding. Commented May 14, 2021 at 5:33

4 Answers 4

2

Use this:

document.getElementById("clickCount").addEventListener("click", function() {
  document.getElementById("showMe").value++;
})
<input type="number" id="showMe" value="1">
<button type="button" id="clickCount">Click Me</button>

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

Comments

1
<form>
   <input type="text" id="clickCount" value="0"/>
   <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>

function incrementValue()
{
    var value = parseInt(document.getElementById('clickCount').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('clickCount').value = value;
}

Comments

1

You can increase the current value of the element on each click. I will also suggest you to avoid inline event handler.

Demo:

document.getElementById('clickCount').addEventListener('click', function(){
   document.getElementById('showMe').value++;
});

//similarly you can decrease
document.getElementById('decrease').addEventListener('click', function(){
   document.getElementById('showMe').value--;
});
<button type="button" id="clickCount" value="click me">+</button>
<input type="number" id="showMe" value="1">
<button type="button" id="decrease" value="click me">-</button>

Comments

1

Use this : Click Me

  const addNumber = document.getElementById("clickCount");
  const showNum = document.getElementById("showMe");
  addNumber.onclick = () => {
    showNum.value++;
  };

Comments

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.