How to use javascript for html form validation to valid number only? -
how validate input form using javascript stretch user don't insert value input form element. object: 1, want user input number value if have character or special character show errors 2, , if user let input element value empty alert user
below javascript code
<script type="text/javascript"> $(document).ready(function(){ $('.quantity, .unitprice').on('keyup', function(e){ var errors = array[]; var quantity = document.getelementsbyclassname('.quantity').val(); var unitprice = document.getelementsbyclassname('.unitprice').val(); if(quantity== ""){ errors = "quantity empty"; } if(unitprice== ""){ errors = "unitprice empty"; }eles{ if(errors){ forearch(errors errors){ alert(errors); } }else{ calculate(); } } }); function calculate(){ var qty = parsefloat( $('.quantity').val() ), unit = parsefloat( $('.unitprice').val() ); if( isnan(qty) || isnan(unit) ) { $('.result').text(''); return false; } var total = qty * unit; $('.result').text(total); } }); </script>
and here html form
<td><?php echo form_input('quantity','',' class="quantity form-control"')?></td> <td><?php echo form_input('unitprice','',' class="unitprice form-control"')?></td> <td><label class="result"></label>$</td>
try example:
$(function() { $(".quantity, .unit").on('input', function() { this.value = this.value.replace(/[^0-9]/g, '');//<-- replace other digits }).on('focusout', function() { if (!this.value) {//<-- if empty alert('required !'); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="quantity" placeholder="quantity"> <input type="text" class="unit" placeholder="unit">
edit: multiple input using common class
$(function() { $(".digits").on('input', function() {//<-- common this.value = this.value.replace(/[^0-9]/g, ''); //<-- replace other digits }).on('focusout', function() { if (!this.value) { //<-- if empty alert('required !'); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="one digits" placeholder="one"> <input type="text" class="two digits" placeholder="two"> <input type="text" class="three digits" placeholder="three"> <input type="text" class="four digits" placeholder="four">
for multiple input without class(not recommended, unless have input on entire page)
$(function() { $("input:text").on('input', function() {//<-- common this.value = this.value.replace(/[^0-9]/g, ''); //<-- replace other digits }).on('focusout', function() { if (!this.value) { //<-- if empty alert('required !'); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" placeholder="one"> <input type="text" placeholder="two"> <input type="text" placeholder="three"> <input type="text" placeholder="four">
Comments
Post a Comment