开发者

Unable to check required fields with click event

I'm trying to check my input fields for values after a user clicks my form button but it's not getting into the input loop to check required fields. Does this not work with a click event? Here is what I'm calling

$('#submit_button').click(function(){

    var formValid = true;

    $(".required input").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).addClass("error_msg");
            formValid = false;
        }
        else{
            $(this).removeClass("error_msg");
        }
    });
    // post form if no errors are seen

});

My input HTML looks like this:

<input class=开发者_StackOverflow社区"required" type="text" value="" name="test" id='test_id' size="80"/>

What am I missing? This seems like it should work...


Try

$("input.required")

instead of

$(".required input")

You can submit your form with jQuery submit function:

$('#submit_button').click(function(){

    var formValid = true;

    $("input.required").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).addClass("error_msg");
            formValid = false;
        }
        else{
            $(this).removeClass("error_msg");
        }
    });

    if(formValid) $('#yourForm').submit();
    else return false; //if the button is a submit
});


Use $('input.required') instead. If you use $('.required input'), it will then look for any input element, inside the .required class. Which in this case, there would be none.


You need to use event.preventDefault() to prevent the form submission.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜