Saikat
Saikat

Reputation: 420

Call a function after Html5 Validation success

I have Some text boxes and one submit button. I have Used HTML5 'required' validation. Its working fine. Now I want to call a function in button click when HTML5 validation does not find any Error. When The required field is not provided the button click will not call the function.

Upvotes: 2

Views: 3903

Answers (4)

Amir Aslam
Amir Aslam

Reputation: 383

Use jquery to trigger function after HTML5 form validation

 <form id="myForm">
       <input type="text" class="input-text" required>
       <input type="submit" id="submit" class="input-button" disabled>
    </form>


    $("myForm").submit(function(){
        // Your code    
     })

Upvotes: 1

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

You're going to need some extra help to do this, it could be in the form of plain javascript. Personally, I'd use jQuery to help out as it will make things easier for you and account for any cross-browser consistencies. Whether or not you want to use jQuery your is choice, whether it's appropriate only for this is another conversation, the following example is just a demonstration.

Here's a hypothetical example using jQuery that achieves your validation listening functionality:

HTML

<form>
    <input type="text" class="input-text" required>
    <input type="text" class="input-text" required>
    <input type="submit" id="submit" class="input-button" disabled>
</form>

​ JS

$textInputs = $('input.input-text');
$textInputs.on('keyup', function() {
    var $validTextInputs = $('input.input-text:valid'),
        $submit = $('#submit');
    console.log($textInputs.length, $validTextInputs.length);
    if($textInputs.length === $validTextInputs.length){
        //all text fields are valid
        $submit.attr('disabled', null);
    } else {
        //not all text fields are valid
        $submit.attr('disabled', '');
    }
});​

CSS (only let's us know, visually, when the input is valid)

.input-text:valid {
    background: green;
}​

See the example in action here: http://jsfiddle.net/m6QXc/

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

You can use the form.onsubmit handler. Assuming the form's ID is form:

var form = document.getElementById("form");
form.onsubmit = function() {
    //Pre-submission validation.

    //Return true or false based on whether the validation passed.
    //return false will prevent the submission the form.
};

Upvotes: 4

Mauno V&#228;h&#228;
Mauno V&#228;h&#228;

Reputation: 9788

Well, you could try this: fiddle example extend it as you need, used jQuery though. You can add whatever you want inside:

 $('#exampleForm').submit(function(e){     
          e.preventDefault();     

          // here you can call your own js methods, send form with ajax? 
          // or what ever you want
      });

Upvotes: 0

Related Questions