user3454272
user3454272

Reputation: 51

form not submitting issue

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
    });

});

Upvotes: 0

Views: 31

Answers (2)

Raja Sekar
Raja Sekar

Reputation: 2130

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.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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
    });

});

Upvotes: 1

Related Questions