0

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
 });
});
beresfordt
5,26210 gold badges37 silver badges43 bronze badges
asked Mar 30, 2015 at 15:19
1
  • Well you do nothing with the validate code. You call it, return a boolean, but never check what is returned. Commented Mar 30, 2015 at 15:22

2 Answers 2

1

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
 });
});
answered Mar 30, 2015 at 15:20
Sign up to request clarification or add additional context in comments.

3 Comments

that mean if I have a value in text box ,form will submit.If I don't have a value it will show an alert and page won't submit.?
that means var x=validate();.IF x==true { call ajax }.Am I right ?
yes... logically yes.... var x = validate(); if (x == false) { return } //ajax here
0

keep 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.

answered Mar 30, 2015 at 15:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.