Hiago_RaD
Hiago_RaD

Reputation: 41

Page reloads when input type="number" is changed by buttons

To simplify I have a basic HTML structure where inside an I have one number input and it's respective add and subtracts buttons. Every time one of the buttons it's clicked the page automatically reloads. How do I prevent that from happening?

This is my code:

<form>
  ...
  <button   onclick="this.parentNode.querySelector('input[type=number]').stepDown()" class="icon-number ver"></button>
<input class="quantity" min="0" max="99" name="quantity" value="1" type="number">
<button onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="plus icon-number ver"></button>
  
  <button class="btn-form btn-add-cart" type="submit">ADD TO CART</button>
  
</form>

The issue disappears when I remove the form tag, but I would like to keep it. I am not using any javascript on this code, it's just HTML.

Upvotes: 1

Views: 571

Answers (2)

symlink
symlink

Reputation: 12208

Make sure your functions are returning false

<form>
  ...
  <button   onclick="this.parentNode.querySelector('input[type=number]').stepDown(); return false;" class="icon-number ver"></button>
<input class="quantity" min="0" max="99" name="quantity" value="1" type="number">
<button onclick="this.parentNode.querySelector('input[type=number]').stepUp(); return false;" class="plus icon-number ver"></button>
  
  <button class="btn-form btn-add-cart" type="submit">ADD TO CART</button>
  
</form>

Upvotes: 1

Fabio Assuncao
Fabio Assuncao

Reputation: 624

It may be submitting the form after you click the button. I tried your code at my local machine and could fix it using attribute type like this.

<button type="button" onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="plus icon-number ver"></button>

Upvotes: 2

Related Questions