T. Ou
T. Ou

Reputation: 91

How to make buttons that increment and decrement a value when clicked?

I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?

<body>
  <input type=button value="increment" onclick="button1()" />
  <input type=button value="decrement" onclick="button2()" />
  <script type="text/javascript">
    var x = 0
    document.write(x)

    function button1() {
      document.write(x++)
    }
    function button2(){
      document.write(x--)   
    }
  </script>
</body>

Upvotes: 6

Views: 31846

Answers (9)

MR SAIF
MR SAIF

Reputation: 1

Here's another way to increment and decrement values using HTML and JavaScript:

<body>
  <p>Increment and Decrement Counter</p>

  <button id="minusButton" onclick="minusPressed()">-</button>
  <input id="count" type="number" value="0" />
  <button id="plusButton" onclick="plusPressed()">+</button>

  <script>
    let count = document.getElementById("count")
    console.log(count.value)

    function plusPressed() {
      count.value++
    }

    function minusPressed() {
      count.value--
    }
  </script>
</body>

Upvotes: 0

Naeem Akhtar
Naeem Akhtar

Reputation: 1192

You are replacing the value of x by document.write();

There should be a different container on document to hold the value of x.

The simple solution could be like this.

<input type=button value="increment" onclick="btnIncrement()" />
<input type=button value="decrement" onclick="btnDecrement()" />
<div id='output'></div>


var x = 0

function btnIncrement () {
   document.getElementById('output').innerText = ++x;
}
function btnDecrement () {
   document.getElementById('output').innerText = --x;
}

Upvotes: 0

Pietro
Pietro

Reputation: 177

This question is very common. I have developed a solution with Bootstrap and pure JavaScript in another very similar thread here. There is autoincrement input on keeping button pressed down. Use ontouchstart and ontouchend instead than onmousedown and onmouseup method for mobile. To make it work for both mobile and desktop browser without headache use onpointerdown, onpointerup, onpointerleave

https://stackoverflow.com/a/70957862/13795525

function imposeMinMax(el) {
    if (el.value != '') {
        if (parseInt(el.value) < parseInt(el.min)) {
            el.value = el.min;
        }
        if (parseInt(el.value) > parseInt(el.max)) {
            el.value = el.max;
        }
    }
}


var index = 0;
var interval;
var timeout;
var stopFlag=false;

function clearAll(){
   clearTimeout(timeout);
   clearInterval(interval);
}


function modIn(el) {
   var inId = el.id;
   if (inId.charAt(0) == 'p') {
      var targetId = inId.charAt(2);      
      var maxValue = Number(document.getElementById(targetId).max);
      var actValue = Number(document.getElementById(targetId).value);
      index = actValue;
      if(actValue < maxValue){
         stopFlag=false;
         document.getElementById(targetId).value++;
      }else{
      stopFlag=true;
      }
      timeout = setTimeout(function(){
      interval = setInterval(function(){        
         if(index+1 >= maxValue){
            index=0;
            stopFlag=true;
         }  
         if(stopFlag==false){
            document.getElementById(targetId).value++;
         } 
         index++;
      }, 100);
      }, 500);      
   imposeMinMax(document.getElementById(targetId));
   }
   if (inId.charAt(0) == 'm') {
      var targetId = inId.charAt(2);
      var minValue = Number(document.getElementById(targetId).min);
      var actValue = Number(document.getElementById(targetId).value);
      index = actValue;
      if(actValue > minValue){
         stopFlag=false;
         document.getElementById(targetId).value--;
      }else{
         stopFlag=true;
      }
      timeout = setTimeout(function(){
         interval = setInterval(function(){        
            if(index-1 <= minValue){
               index=0;
               stopFlag=true;
            }  
            if(stopFlag==false){
               document.getElementById(targetId).value--;
            } 
            index--;
         }, 100);
         }, 500);      
      imposeMinMax(document.getElementById(targetId));
   }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Button example</title>
  <meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>

  <button type='button' class='btn btn-danger btn-sm ' id='mbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
  <input type='number' id='A'  onchange='imposeMinMax(this)' value='200' max='350' min='150' step='1' style='width: 50px;'>                 
  <button type='button' class='btn btn-danger btn-sm ' id='pbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>&nbsp;

  <button type='button' class='btn btn-danger btn-sm signBut' id='mbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
  <input type='number'  id='B'  onchange='imposeMinMax(this)' value='250' max='450' min='150' step='1' style='width: 50px;'>                 
  <button type='button' class='btn btn-danger btn-sm ' id='pbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>&ensp;

  <button type='button' class='btn btn-danger btn-sm signBut' id='mbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
  <input type='number'  id='C'  onchange='imposeMinMax(this)' value='3' max='10' min='1' step='1' style='width: 50px;'>                 
  <button type='button' class='btn btn-danger btn-sm ' id='pbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>

</body>



</html>

Upvotes: 0

Khaydarov Marufjon
Khaydarov Marufjon

Reputation: 131

var x = 1;
document.getElementById('output-area').innerHTML = x;
function button1() {
  document.getElementById('output-area').innerHTML = ++x;

}
function button2() {
  if(x <= 0 ){
    alert(' minimum value 0 // By Khaydarov Marufjon marvell_it academy uzb ')
    return false ;
  }
  document.getElementById('output-area').innerHTML = --x;
}
input{
  width: 70px;
   background-color: transparent;
   padding: 20px;
   text-align: center;
 }
 button{
   padding: 20px;
 }
<input type='button' value="plus" onclick="button1()" />
<span id="output-area"></span>
<input type='button' value="minus" onclick="button2()" />

Upvotes: 0

Aijaj Hussain Ansari
Aijaj Hussain Ansari

Reputation: 375

HTML code for UI

<div class="card">
      <div class="card-body">
       <h5 class="card-title">How many guests can stay?</h5>
       <div class="row">
       <ul class="guestCounter">
          <li data-btn-type="increment"><span class="romoveBtn"><i class="fa fa-plus"></i></span> </li>
          <li class="counterText"><input type="text" name="guestCount" id="btnGuestCount" value="1" disabled /> </li>
        <li data-btn-type="decrement"><span class="romoveBtn"><i class="fa fa-minus"></i></span></li>
       </ul>
  </div>

Java Script:

// set event for guest counter
$(".guestCounter li").on("click", function (element) {
    var operationType = $(this).attr("data-btn-type");
    //console.log(operationType);
    var oldValue = $(this).parent().find("input").val();
    //console.log(oldValue);

    let newVal;
    if (operationType == "increment") {
         newVal = parseFloat(oldValue) + 1;
    } else {
        // Don't allow decrementing below zero
        if (oldValue > 1) {
             newVal = parseFloat(oldValue) - 1;
        } else {
            newVal = 1;
        }
    }
    $(this).parent().find("input").val(newVal);
});

enter image description here

Upvotes: 1

PeterMader
PeterMader

Reputation: 7285

The document.write is the problem. It only works before the browser is done loading the page completely. After that, document.write doesn't work. It just deletes all of the existing page contents.

Your first document.write is executed before you the page has loaded completely. This is why you should see the 0 next to the two buttons.

Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write will be called, which doesn't work at that point, because the page already has loaded completely.


document.write shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span> element and update it's content using textContent.

Moreover, use addEventListener instead of inline event listeners:

var x = 0;
var span = document.querySelector('span'); // find the <span> element in the DOM
var increment = document.getElementById('increment'); // find the element with the ID 'increment'
var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'

increment.addEventListener('click', function () {
  // this function is executed whenever the user clicks the increment button
  span.textContent = x++;
});

decrement.addEventListener('click', function () {
  // this function is executed whenever the user clicks the decrement button
  span.textContent = x--;
});
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>

As others have mentioned, the first x++ won't have a visible effect, because the value of x is incremented after the content of the <span> is updated. But that wasn't not your original problem.

Upvotes: 2

Angelos Chalaris
Angelos Chalaris

Reputation: 6747

The problem is that you put ++ and -- after the variable, meaning that it will increment/decrement the variable after printing it. Try putting it before the variable, like below.

Also, as mentioned, you have some trouble with document.write(). Consider the following documentation from the W3Schools page:

The write() method writes HTML expressions or JavaScript code to a document.

The write() method is mostly used for testing. If it is used after an HTML document is fully loaded, it will delete all existing HTML.

Thus, document.write() will remove all your existing content as soon as you click on a button. If you want to write to the document, use an element's .innerHTML like this:

var x = 0;

document.getElementById('output-area').innerHTML = x;

function button1() {
  document.getElementById('output-area').innerHTML = ++x;
}

function button2() {
  document.getElementById('output-area').innerHTML = --x;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>

Upvotes: 9

document write will delete full html: The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML. As in w3schools

try this instead

<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<div id="value"></div>
<script type="text/javascript">
    var x=0

    var element = document.getElementById("value");
    element.innerHTML = x;

    function button1(){
        element.innerHTML = ++x;
    }
    function button2(){
        element.innerHTML = --x;
    }
</script>

I changed the x-- and x++ to ++x and --x so the changes are immediatly. With this change your code would have worked aswell. showing 1 or -1.

Upvotes: 2

p.mathew13
p.mathew13

Reputation: 921

Why don't you change your code a bit? Instead of document.write(x++) and document.write(x--) use document.write(++x) and document.write(--x).

Upvotes: 4

Related Questions