I have a code snippet like this.When I submit it shows alert button and ajax function calls.How can I prevent.I have a textbox with id=id1.I need to call ajax only if there is a value in textbox.
I have also another button in same page so I need to call common validate function inside that button also.So I wrote common function.
$( document ).ready(function() {
function validate() {
if($('#id1').val=='') {
alert('enter a value');
return false;
}
return true;
}
$('#button').click(function() {
validate();
$.ajax...code goes here
});
});
-
Well you do nothing with the validate code. You call it, return a boolean, but never check what is returned.epascarello– epascarello2015年03月30日 15:22:33 +00:00Commented Mar 30, 2015 at 15:22
2 Answers 2
If it is not valid, return from the click handler without executing the ajax call.
In your case you are calling the validate method but you are not doing anything with the value returned from it. So use a if condition to check whether it is true or false, if false then return from the click handler
$(document).ready(function () {
function validate() {
if ($('#id1').val() == '') {
alert('enter a value');
return false;
}
return true;
}
$('#button').click(function () {
if (!validate()) {
return;
}
$.ajax...code goes here
});
});
3 Comments
var x = validate(); if (x == false) { return } //ajax herekeep your functions out of jquery functions, to make it reusable across other places.
$( document ).ready(function() {
$('#button').click(function() {
var isValid = validate();
if(isValid){
$.ajax...code goes here
}
});
});
var validate = function() {
if($('#id1').val=='') {
alert('enter a value');
return false;
}
return true;
}
Return the validity of the check box and if it is true then trigger the ajax request.