避免发送任何字段为空的Axax

avoid sending if any field empty Axax

本文关键字:Axax 字段 任何      更新时间:2023-09-26

在我的表单中,我有各种字段,包括(输入和选择),我想在其中检查任何空字段,并在任何字段为空时阻止ajax调用,并专注于空字段。到目前为止,我正在尝试这种方式,它发出警报,但也发出ajax调用。

$('#submit').click(function() {
    $('input').each(function() {
        if (!$(this).val()) {
            alert('Some fields are empty');
            return false;
        }
    });
    event.preventDefault(); // using this page stop being refreshing 
    $.ajax({
        type: 'POST',
        url: "<?php echo site_url(''); ?>/shipment/create_shipment",
        data: $('form').serialize(),
        cache: false,
        success: function(data) {
            $('#F_id').val('');
            $('#v_id').val('');
            $('#shp_no').val('');
            $('#shipDate').val('');
            $('#sup').val('');
            $('#sup-quantity').val('');
            $('#box').val('');
            $('#box-quantity').val('');
            $("#sup").prop('disabled', true);
            $("#sup-quantity").prop('disabled', true);
            $("#box").prop('disabled', true);
            $("#box-quantity").prop('disabled', true);
            $('.alert-success').fadeOut(200).show();
            $('.alert-danger').fadeOut(200).hide();
            /// alert('form was submitted');
        },
        error: function(data) {
            $('.alert-success').fadeOut(200).hide();
            $('.alert-danger').fadeOut(200).show();
        }
    });
});

return falseeach函数返回,而不是从click函数返回。

尝试使用bool变量表示有效,否则返回false。

var valid = true;
e.prevent.preventDefault(); // e being event variable in submit
$('input').each(function() {
    if(!$(this).val()){
        alert('Some fields are empty');
        valid = false;
        return false;
    }
});
if(!valid) return false;
//.....

希望这能有所帮助。