PythonEnthusiast PythonEnthusiast - 1 month ago 6
jQuery Question

jQuery - Form not validating

In the following form when I hit submit, it alerts

111
, but does not send an ajax request. It instead sends a page-refreshing submit request. Why?

<form id="post_answer_form" method="POST" action="some_url">
<fieldset>
<textarea id="qanswer" name="qanswer"></textarea>
<button type="submit">Post Your Answer </button>
<button type="submit" style="display: none;">Update </button>
</fieldset>
</form>


I'm validating it against some rules as follows:

$(document).on('submit', '#post_answer_form', function(){
alert(111)
tinymce.triggerSave();
}).validate({
ignore: '',
rules: {
qanswer: {
required: true,
}
},
submitHandler: function(form) {
alert(111)
$.ajax({
...
});
return false
},
});

Answer

Your validation is not working because you are not applying validate on form . you can try following code.

$(function(){   
    $('#post_answer_form').submit(function(e) {
        e.preventDefault();    
        tinymce.triggerSave();
        if($('#post_answer_form').valid()){
            // Submit form using ajax or using .submit() 
            $.ajax({
                ...
            });
        }
    }); 

    $('#post_answer_form').validate({
        ignore: '',
        onsubmit : false,
        rules: {
            qanswer: {
                required: true,
            }
        }
    });
});
Comments