Reputation: 231
I have a validation function which I used other stackoverflow questions to write but this function is not working. The validation is done on an input field with javascript. It should only accept numbers (no zeros, signs, alphabets). Does any one have any suggestion?
$(document).ready(function () {
$(".myQuantityClass").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57 || e.which == 48)) {
return false;
}
});
});
Here is the html:
<tr>
<td class='quantity'><input type='text' class='myQuantityClass' value='1' another_id="+product_id+" onkeyup='addQuantity(this," + price + ");'></td></tr>
Upvotes: 0
Views: 36
Reputation: 26908
Just return when the key is correct..
<input type='text' class='myQuantityClass' value='1' onkeyup='addQuantity();'><br/>
<input type='text' class='myQuantityClass' value='1' onkeyup='addQuantity();'><br/>
<input type='text' class='myQuantityClass' value='1' onkeyup='addQuantity();'><br/>
<span id='total'></span>
<script src='jquery.js'></script>
<script>
$(document).ready(function () {
$(".myQuantityClass").keypress(function (e) {
var k = e.which;
if ((k > 48 && k < (48+10)) || k == 8 || k == 0) return;
return false;
});
});
function addQuantity() {
var total = 0;
$(".myQuantityClass").each(function(idx,el){
total += el.value|0;
});
$('#total').text(total);
}
</script>
Upvotes: 1
Reputation: 8193
demo here --> http://jsfiddle.net/ebzsdk88/1/
$(".myQuantityClass").keypress(function (e) {
return (e.which>48 && e.which<58);
});
Upvotes: 1