1

I want to create a small count button but don't know how to make it in JavaScript... Here's the code :

HTML

<div id="input_div">
    <input type="text" size="25" value="0" id="count">
    <input type="button" value="-" id="moins">
    <input type="button" value="+" id="plus">
</div>

It must increase AND decrease the number in the input[type=text] when click on the -/+ button.

Can someone help me ?

4
  • Is manual entry of number allowed in the text box? Commented May 29, 2013 at 12:53
  • I want the count to change without changing anything in the html. Just using js so. And yes it's allowed but it's not the objective Commented May 29, 2013 at 12:57
  • So if someone enters 37 into the box, should the + then increase to 38, or should it increase from where it was before manual entry. Commented May 29, 2013 at 12:57
  • I understand now, it shouldn't increase from the manual entry. Anyway, it works as I wanted so the topic's closed, thank you for your responses ! Commented May 29, 2013 at 13:12

5 Answers 5

5

You'd need two things.

  • Variables - which are the way to store information in JavaScript
  • Event handlers, which are the way to react to events in JavaScript

First, let's create a script tag, and put a JavaScript count variable in it, we'll put it in the bottom of our body tag:

<script>
    var count = 0;
</script>

Now, we want to create a handler, that is something that executes whenever the plus and minus signs are clicked

<script>
    var count = 0;
    function plus(){
        count++;
    }
    function minus(){
        count--;
    }
</script>

We've created two functions to call when the buttons are clicked, but we do not update the value in the HTML, or call them yet, let's update the value in the HTML.

We'll do so by document.getElementByID for the element to update and then change its value. Our script tag should look something liks this:

<script>
    var count = 0;
    var countEl = document.getElementById("count");
    function plus(){
        count++;
        countEl.value = count;
    }
    function minus(){
        count--;
        countEl.value = count;
    }
</script>

One last thing, we need to tell the elements in the DOM to execute those handlers.

<div id="input_div">
    <input type="text" size="25" value="0" id="count">
    <input type="button" value="-" id="moins" onclick="minus()">
    <input type="button" value="+" id="plus" onclick="plus()">
</div>

We've added them as event handlers to the DOM reacting to a click on the buttons, completing the task.

Now, here are some things we can improve:

  • We can use addEventListener to avoid polluting our DOM, and create unobtrusive JavaScript.
  • We can use a more advanced tool like KnockoutJS to handle binding the value we have to the DOM element instead of updating it ourselves.
  • We can read Eloquent JavaScript and learn more about how the language works!

Good luck, happy JavaScripting, and happy learning :)

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

7 Comments

Why not show him an example of unobtrusive Javascript. Instead, he's now learning bad practices.
You're welcome! @crush Good question! I don't want to complicate things for a first timer, most of my answer focuses and what and why we're doing and not the actual code. There are plenty of examples OP can look at at the MDN page for addEventListener which I linked to.
If he's brand new, then it's not complicating anything. It's showing him the right way to do it instead of spreading bad practices to beginners. Imagine how confused he will be now when (if) he is introduced to unobtrusive JavaScript.
@crush Introducing event listeners as the first things can be extremely confusing to people who do not hail from event based languages. I say this from personal experience of years teaching programming, I tried starting from event listeners and most of my students found it more confusing. While a correct solution would be using addEventListener and not the onclick attribute which both of us used in our solution, it would complicate things needlessly. For example, if OP forgot to put the script at the bottom of his body, it wouldn't work.
@crush If you want to continue discussing this, comments are not the place for discussion about this sort of thing, I'm here chat.stackoverflow.com/rooms/17/javascript often, and for the next few hours, ping me
|
2

DEMO FIDDLE FOR JAVASCRIPT

code html -

<div id="input_div">
 <input type="text" size="25" value="0" id="count" />
 <input type="button" value="-" id="minus" onClick = "doMinus();" />
 <input type="button" value="+" id="plus" onClick = "doPlus();" />
</div>

code javaScript -

function doMinus(){
 document.getElementById("count").value = --document.getElementById("count").value;
}

function doPlus(){
 document.getElementById("count").value = ++document.getElementById("count").value;
}

jQuery Version

DEMO FIDDLE FOR JQUERY

code html -

<div id="input_div">
  <input type="text" size="25" value="0" id="count" />
  <input type="button" value="-" id="minus" />
  <input type="button" value="+" id="plus" />
</div>

code jQuery -

$('#minus').click(function(){
  $("#count").val(parseInt($("#count").val())-1);
});
$('#plus').click(function(){
  $("#count").val(parseInt($("#count").val())+1);
});

2 Comments

I don't remember him saying jQuery was an option.
Please don't answer with jQuery to non jQuery questions, we're trying to teach people how to use the language here, not how to use a library. OP would have to import 80KB of code just to increase a counter which sounds absurd. Moreover, you do not cache your selectors, and you treat the DOM as a source of knowledge.
0

U can write some script as shown

<script>            
            function increase(){
                var a = 1;
                var textBox = document.getElementById("count");
                textBox.value = a;
                a++;
            }            
        </script>

<body>
        <button type="button" onclick="increase()">+</button>
        <input type="text" id="text">
    </body>

similarly u can do it for - decrease button

Comments

0

in this case, I use input type range that display a slider : <input type="range" id="myInputRange" value="15" min="0" max="50" step="1" onchange="document.getElementById('output').textContent=value" ><span id="output">15</span> (instead of input type number that is not supported by IE)

Comments

-2

This seems pretty simple.

(function() {
    var count = 0;

    var minusButton = document.getElementById("moins");
    var plusButton  = document.getElementById("plus");
    var countBox    = document.getElementById("count");

    minusButton.onclick = function(e) {
        countBox.value = --count;
    };

    plusButton.onclick = function(e) {
        countBox.value = ++count;
    };
})();

4 Comments

i don't remember him saying increment in minus
I'm not the down-voter, but I'd appreciate avoiding terms like "ridiculously simple.". That's extremely off-putting to new developers who are yet to grasp how the language, functions or the DOM work.
Then they should take a tutorial. He didn't even attempt to write the Javascript.
@rohit fixed. simple mistake.

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.