简体   繁体   中英

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

});

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

});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM