仅在验证通过时将数据提交到数据库

时间:2015-05-19 14:49:04

标签: javascript jquery forms validation

我已经尝试过在不同的网站上研究这个问题,但是无法完成它可能是因为我不熟悉编程。这是我的代码。它发送数据然后要求验证,而不是它应该清除验证然后将数据发送到数据库。需要帮助

var createAllErrors = function() {
        var form = $( this ),
            errorList = $( "ul.errorMessages", form );

        var showAllErrorMessages = function() {
            errorList.empty();

            // Find all invalid fields within the form.
            var invalidFields = form.find( ":invalid" ).each( function( index, node ) {

                // Find the field's corresponding label
                var label = $( "label[for=" + node.id + "] "),
                    // Opera incorrectly does not fill the validationMessage property.
                    message = node.validationMessage || 'Invalid value.';

                errorList
                    .show()
                    .append( "<li><span>" + label.html() + "</span> " + message + "</li>" );
            });
        };
    // Support Safari
        form.on( "submit", function( event ) {
            if ( this.checkValidity && !this.checkValidity() ) {
                $( this ).find( ":invalid" ).first().focus();
                event.preventDefault();
            }
        });

        $( "input[type=submit], button:not([type=button])", form )
            .on( "click", showAllErrorMessages);

        $( "input", form ).on( "keypress", function( event ) {
            var type = $( this ).attr( "type" );
            if ( /date|email|month|number|search|tel|text|time|url|week/.test ( type )
              && event.keyCode == 13 ) {
                showAllErrorMessages();
            }
        });
    };

$( "form" ).each( createAllErrors );

$('.submit-btn').click(function(){

    var data = $('.form-horizontal :Input').serializeArray();
    //now the data is sent to server database using .post(sent url, data to be sent, result when successfully sent data)
    $.post($('.form-horizontal').attr('action'), data, function(info){$('#result').html(info); });

    clearInput();
    });

$('.form-horizontal').submit( function(){
    return false;
});

function clearInput () {
    $('.form-horizontal :Input').each( function(){
        $(this).val('') ;
    });
};  

0 个答案:

没有答案