1

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.

Hiago_RaD
  • 41
  • 6
  • Post a [mcve] please, including your JavaScript – j08691 Jan 16 '20 at 19:18
  • @j08691 I am not using any javascript, the problem it's reproduced when you run the code snippet – Hiago_RaD Jan 16 '20 at 19:27
  • 1
    Running your snippet in Chrome on Windows does nothing when changing the number input via the arrows. If you're referring to the *buttons* in the form well then that's the expected behavior as the default type for buttons is submit. Change it to something like button and it doesn't submit the form. – j08691 Jan 16 '20 at 19:29
  • https://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms – j08691 Jan 16 '20 at 19:32
  • Thanks @j08691 that fixed it. – Hiago_RaD Jan 16 '20 at 19:39

2 Answers2

2

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>
Fabio Assuncao
  • 624
  • 4
  • 12
1

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>
symlink
  • 11,984
  • 7
  • 29
  • 50