[javascript] javascript onclick increment number

With javascript, how can I do it so when i click a form button it adds 1 to a number? The number it increments could be in a form text field or something.

Obviously it'd be on onclick but I'm not sure of the code.

This question is related to javascript onclick numbers

The answer is


No need to worry for incrementing/decrementing numbers using Javascript. Now HTML itself provides an easy way for it.

<input type="number" value="50">

It is that simple.The problem is that it works fine only in some browsers.Mozilla has not yet supported this feature.


For those who do NOT want an input box, here's a ready-to-compile example you can check out, which just counts the button clicks, updates them in the text and toggles the font. You could take the value and use it anywhere you see fit.

<!DOCTYPE html>
<html>


<body>
<p id="demo">JavaScript can change the style of an HTML element.</p>

<script>
   function incrementValue()
        {
            var demo_id = document.getElementById('demo')
            var value = parseInt(demo_id.value, 10);
            // if NaN, set to 0, else, keep the current value
            value = isNaN(value) ? 0 : value;
            value++;
            demo_id.value = value;

            if ((value%2)==0){
                demo_id.innerHTML = value;
                demo_id.style.fontSize = "25px"; 
                demo_id.style.color = "red";
                demo_id.style.backgroundColor = "yellow";   
            } 
            else {
                demo_id.innerHTML = value.toString() ;
                demo_id.style.fontSize = "15px"; 
                demo_id.style.color = "black";
                demo_id.style.backgroundColor = "white";
            }
        }
</script>

<form>
    <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>
</body>


</html>

In its most basic incarnation..

JavaScript:

<script>
    var i = 0;
    function buttonClick() {
        document.getElementById('inc').value = ++i;
    }
</script>

Markup:

<button onclick="buttonClick()">Click Me</button>
<input type="text" id="inc" value="0"></input>

<body>
    <input type="button" value="Increase" id="inc" onclick="incNumber()"/>
    <input type="button" value="Decrease" id="dec" onclick="decNumber()"/>

    <label id="display"></label>

    <script type="text/javascript">

    var i = 0;

    function incNumber() {
        if (i < 10) {
            i++;
        } else if (i = 10) {
            i = 0;
        }
        document.getElementById("display").innerHTML = i;
    }

    function decNumber() {
        if (i > 0) {
            --i;
        } else if (i = 0) {
            i = 10;
        }
        document.getElementById("display").innerHTML = i;
    }
    </script>
</body>

jQuery Example

_x000D_
_x000D_
var $button = $('.increment-btn');
var $counter = $('.counter');

$button.click(function(){
  $counter.val( parseInt($counter.val()) + 1 ); // `parseInt` converts the `value` from a string to a number
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="1" class="counter"/>
<button type="button" class="increment-btn">Increment</button>
_x000D_
_x000D_
_x000D_

'Plain' JavaScript Example

_x000D_
_x000D_
var $button = document.querySelector('.increment-btn');
var $counter = document.querySelector('.counter');

$button.addEventListener('click', function(){
  $counter.value = parseInt($counter.value) + 1; // `parseInt` converts the `value` from a string to a number
}, false);
_x000D_
<input type="text" class="counter" value="1"/>
<button type="button" class="increment-btn">Increment</button>
_x000D_
_x000D_
_x000D_


Check this out.

_x000D_
_x000D_
var timeout_;

function mouseDown_i() {
  value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
  document.getElementById('xxxx').value = value + 1;  
  timeout_ = setTimeout(function() { mouseDown_i(); }, 150);
}

function mouseDown_d() {
  value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
  value - 1 <= 0 ? document.getElementById('xxxx').value = '' : document.getElementById('xxxx').value = value - 1;  
  timeout_ = setTimeout(function() { mouseDown_d(); }, 150);
}

function mouseUp() { clearTimeout(timeout_); }

function mouseLeave() { clearTimeout(timeout_); }
_x000D_
<p onmousedown="mouseDown_i()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to INCREMENT!</p>
<p onmousedown="mouseDown_d()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to DECREMENT!</p>
<input id="xxxx" type="text" value="0">
_x000D_
_x000D_
_x000D_


I know this is an old post but its relevant to what I'm working on currently.

What I'm aiming to do is create next/previous page buttons at the top of a html page, and say I'm on 'book.html', with the current 'display' ID content being 'page-1.html' through ajax, if i click the 'next' button it will load 'page-2.html' through ajax, WITHOUT reloading the page.

How would I go about doing this through AJAX as I have seen many examples but most of them are completely different, and most examples of using AJAX are for WordPress forms and stuff.

Currently using the below line will open the entire page, I want to know the best way to go about using AJAX instead if possible :) window.location(url);

I'm incorportating the below code as an example:

var i = 1;
var url = "pages/page-" + i + ".html";

    function incPage() {
    if (i < 10) {
        i++;
        window.location = url; 
        //load next page in body using AJAX request

    } else if (i = 10) {
        i = 0;
    }
    document.getElementById("display").innerHTML = i;
}

function decPage() {
    if (i > 0) {
        --i;
        window.location = url; 
        //load previous page in body using AJAX request
    } else if (i = 0) {
        i = 10;
    }
    document.getElementById("display").innerHTML = i;
}

Yes! You can definitely use onclick or you can also use addEventListener to listen a click event. In this code sample the onclick event is in action(use).

HTML code:

<div class="container">
<p><output id="output">0</output></p>
<p><button type="button" id="btn">Increment</button></p>
</div>

Javascript code:

(function() {
 var button = document.getElementById("btn")
 var output = document.getElementById("output")
 var number
 var counter
 

 function init() {
 // Convert string to primitve number using parseInt()
  number = parseInt(output.innerText)
  
 /**
 * Start counter by adding any number to start counting.
 * In this case the output starts from 0 so to immediately
 * invoke the button to increment the counter add 1 to start 
 * counting in natural number (counting numbers).
 */  counter = number + 1
  
  function increment() {
    // Increment counter
    value = counter++
    output.innerText = value
   }
  
   // Output the increment value for every click
    button.onclick = increment
 }

 window.onload = init
})()

Demo


var i=0; 
function increment() {           
    i++;       
    document.getElementById('number').innerHTML=i;
}

jQuery Library must be in the head section then.

<button onclick="var less = parseInt($('#qty').val()) - 1; $('#qty').val(less);"></button>
<input type="text" id="qty" value="2">
<button onclick="var add = parseInt($('#qty').val()) + 1; $('#qty').val(add);">+</button>

Simple HTML + Thymeleaf version. Code with Controller

<form action="/" method="post">
                <input type="hidden" th:value="${post.getId_post()}" name="id_post">
                <input type="hidden" th:value="-1" name="valueForChange">
                <input type="submit" value="-">
</form>

This is how it looks - look of buttons you can change with style. https://i.stack.imgur.com/b97N1.png


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to onclick

How to use onClick with divs in React.js React prevent event bubbling in nested components on click React onClick function fires on render Run php function on button click Passing string parameter in JavaScript function Simple if else onclick then do? How to call a php script/function on a html button click Change Button color onClick RecyclerView onClick javascript get x and y coordinates on mouse click

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python