Reputation: 43
I want to setup validation in jQuery. It's not working, what should I do on submit button and jQuery code?
function validate() {
var total = $('#total').val();
var limit = 1000;
if (total > limit) {
alert('numbers cannot exceed the limit');
return false;
} else {
// submit
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="total"></input>
<input type="submit" value="Submit" onclick="validate()">
Upvotes: 0
Views: 49
Reputation: 26
you should use button type instead of submit because submit must be use under the form tag
function validate() {
var total = $('#total').val();
var limit = 1000;
if (total > limit) {
alert('numbers cannot exceed the limit');
return false;
} else {
// submit
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="total"></input>
<input type="button" value="Submit" onclick="validate()">
Upvotes: 0
Reputation: 14208
As @Devsi Odedra comment, you should parse the value to number to be able to compare instead of comparing string as well.
$('#total').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1)
&& (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
function validate() {
var total = parseFloat($('#total').val());
var limit = 1000;
if(total > limit) {
alert('numbers cannot exceed the limit');
return false;
} else {
// submit
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="total"></input> and submit button <input type="submit" value="Submit" onclick="validate()">
Updated
You should validate to only allow input float number like this
$('#total').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Upvotes: 2