admin管理员组

文章数量:1323524

What I am doing is catching the click action on my form's submit button, preventDefault()ing it, doing some putation, and then making an ajax call instead of submitting the form.

Is there a way to use javascript to force the html5 validators to fire even if the form isn't being submitted?

 $('#submitButton').click(function (e) {
        e.preventDefault(); //stop the form from submitting

        //Do putation

        $.post('/ments', values, function(results) {
            hideForm($('#new_ment_' + parentId));
            parent.children('.children').prepend(results);
        }, 'html');
    });

What I am doing is catching the click action on my form's submit button, preventDefault()ing it, doing some putation, and then making an ajax call instead of submitting the form.

Is there a way to use javascript to force the html5 validators to fire even if the form isn't being submitted?

 $('#submitButton').click(function (e) {
        e.preventDefault(); //stop the form from submitting

        //Do putation

        $.post('/ments', values, function(results) {
            hideForm($('#new_ment_' + parentId));
            parent.children('.children').prepend(results);
        }, 'html');
    });
Share Improve this question asked Feb 14, 2012 at 5:53 Razor StormRazor Storm 12.3k20 gold badges95 silver badges151 bronze badges 1
  • Yes I can roll my own validation in javascript, but html5's required="required" tag is nice and simple and sets up a decently looking popup GUI for you. Less work and less code plexity is always a plus, but it ends up taking too much work to use html5's validations I can just make my own javascript ones. – Razor Storm Commented Feb 14, 2012 at 5:53
Add a ment  | 

2 Answers 2

Reset to default 8

It works just fine, I tested in latest Chrome and Firefox. Just e.preventDefault() on the <form>:

html:

<form method="post" action="test.html">
    <input type="text" required></input>
    <input type="submit" value="Submit">
</form>

jQ:

$('form').submit(function(e){ e.preventDefault(); });

example: http://jsfiddle/elclanrs/2nnLc/2/

Using html5 constraints the form object has some new methods. For example you can call checkValidity() on the form object to check the input.

<form method="post" action="test.html" id="myForm">
    <input type="text" required></input>
    <input type="submit" value="Submit" id="submitButton">
</form>

<script type="text/javascript">
    $('#submitButton').click(function (e) {
        e.preventDefault();
        alert($("#myForm").get()[0].checkValidity());
    })
</script>

本文标签: javascriptUse html5 validations even if form is never being submittedStack Overflow