1

I am writting a simple counter which adds or mimus for each click on the respective button. However, I cannot make the text input change accordingly.

<!DOCTYPE html>
<html>
<body>

<div>
    <form>
      <input id="minus" type="button" value="-" onclick="minus()" >
      <input id="num" type="text" name="message" value="10">
      <input id="add" type="button" value="+" onclick="add()" >
  </form>

</div>

<script> 
    var input = document.getElementById("num");


    function add()
    {
        var result = (parseInt(input.value,10) + 1).toString();
        input.value = result;
    }


    function minus()
    {
        var result = (parseInt(input.value,10) - 1).toString();
        input.value = result;
    }
</script>

</body>
</html>

What did I do wrong? Thank you.

0

2 Answers 2

1

You can't use the same ID name and function name. Please try this. It will work.

<div>
<form>
  <input id="minus" type="button" value="-" onclick="minusCount()" />
  <input id="num" type="text" name="message" value="10">
  <input id="adda" type="button" value="+" onclick="addCount()" >
 </form>

</div>

<script> 
var input = document.getElementById("num");


function addCount()
{
    var result = (parseInt(input.value,10) + 1).toString();
    input.value = result;
}


function minusCount()
{
    var result = (parseInt(input.value,10) - 1).toString();
    input.value = result;
}

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

Comments

0

element IDs are global variables

As inline-click handler expects function to be under global-scope(window.FUNCTION_NAME), function-name can not have same name as value of ID attribute

In your example, add/minus are DOMElements/Objects, not a function hence add is not defined ReferenceError is thrown.

console.log(add);
console.log(minus);
<div>
  <form>
    <input id="minus" type="button" value="-" onclick="minusCount()" />
    <input id="num" type="text" name="message" value="10">
    <input id="add" type="button" value="+" onclick="addCount()">
  </form>
</div>

It is recommended to use JavaScript-Event-Binding(addEventListener) instead of Inline-event-handlers

var input = document.getElementById("num");
var add = document.getElementById("add");
var minus = document.getElementById("minus");
add.addEventListener('click', function() {
  input.value = (parseInt(input.value, 10) + 1).toString();
});
minus.addEventListener('click', function() {
  input.value = (parseInt(input.value, 10) - 1).toString();
});
<div>
  <form>
    <input id="minus" type="button" value="-">
    <input id="num" type="text" name="message" value="10">
    <input id="add" type="button" value="+">
  </form>
</div>

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.