how to change input number value

Asked

Viewed 353 times

1

I am facing some difficulties to change the value of an input (as stated in the question).

Follow the code below:

function alteraQtdProduto(op) {
  if (op == 'up') {
    var num = document.getElementById('setQtdProduto').value;
                                document.getElementById('setQtdProduto').textContent = num++;

  }
}
.cart_qtd {
  border: none;
  outline: none;
  padding: 5px;
  border-radius: 5px;
  margin: 0 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, .5);
}
<div style="width: 100%; text-align: center">

  <button type="button" onclick="alteraQtdProduto('down')">-  </button>

  <input id="setQtdProduto" class="cart_qtd" type="number" value="1" min="1">

  <button type="button" onclick="alteraQtdProduto('up')">+</button>

</div>

What was intended:

  • by clicking the + button was for the value in the input to be changed. I tried to implement only the part of increasing the items so far.

P.S.: I just tried to implement the button + items so far.

  • An error appears in the browser console, when you try to increment or when the page loads?

1 answer

4


  1. Its element is a <input>. The same way you used the attribute .value to obtain the value, it is this attribute that you must use to define the new value, instead of the textContent.

  2. .value returns a string. It is necessary to do the conversion with parseInt or parseFloat before making the addition.

  3. Since you are using the same element, you can create a variable pointing to it. Instead of calling getElementById several times.

const qtdProduto = document.getElementById('setQtdProduto');

function alteraQtdProduto(op) {
  if (op == 'up') {
    var num = parseInt(qtdProduto.value);
    qtdProduto.value = num + 1;
  }
}
<div>
  <button type="button" onclick="alteraQtdProduto('down')">-  </button>

  <input id="setQtdProduto" class="cart_qtd" type="number" value="1" min="1">

  <button type="button" onclick="alteraQtdProduto('up')">+</button>

</div>

  • Good, it worked. I thought about it, but I used the typeof the value I took from the input and it returned a number, so I disregarded :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.