How to prevent the number from being less than or equal to 0 in an input type number?

-1

Good evening. I have an input type number (for when ready, my shopping cart can change the quantity)

<td>
   <input 
       type="number" 
       style="width: 50px;"
       id="<?php echo "p" . $a; ?>"
       min="1"
       max="<?php echo $max_produto; ?>"
       value="<?php echo $values["item_quantity"]; ?>"
   >
</td>

My problem is that even setting the min and max, if I change directly in the input without using the arrows I can by the value 0, or less than 0, that when I confirm the purchase it gets the quantity put and not should happen. How can I solve this problem?

    
asked by anonymous 06.06.2018 / 22:23

2 answers

2

There are several ways, one of which is to check the validity.valid property. It will be true if and only if the input is within the range.

<input 
       type="number" 
       style="width: 50px;"
       id="qqid"
       min="1"
       max="11"
       value="" oninput="validity.valid||(value='');" />
  

The only problem with the above solution is that it completely clears the previously entered value when an invalid value is entered.

This can be avoided as follows:

<input 
       type="number" 
       style="width: 50px;"
       id="qqid"
       min="1"
       max="11"
       value="" oninput="validity.valid ? this.save = value : value = this.save;" />
    
07.06.2018 / 02:57
1

Just use the input event through JavaScript .

Following code and explanation:

/* O evento input do DOM é disparado sincronicamente quando o valor de um elemento <input>, <select>, ou <textarea> é alterado. */
document.querySelector("#qualquer-coisa").addEventListener("input", el => {
	
  /* Verifica se o valor alterado é maior que o valor do atributo max */
	if (el.target.value > parseInt(el.target.getAttribute("max"))) {
  
  	/* Caso seja, define o valor do atributo max */
  	el.target.value = el.target.getAttribute("max");
  }
  
  /* Verifica se o valor alterado é menor que 0 */
	if (el.target.value <= parseInt(el.target.getAttribute("min"))) {
  
  	/* Caso seja, define o valor 0 */
  	el.target.value = 1;
  }
})
<input 
       type="number" 
       style="width: 50px;"
       id="qualquer-coisa"
       min="1"
       max="11"
       value="8" />
  

Note: In addition to the input event, you can choose: paste or change

    
06.06.2018 / 22:51