October 10, 2012

capture submit() method

Question by Steffen Maas

I have a form like:

<form method="POST" action="page.html" onsubmit="alert('foo'); // validate();" name="foobar">
...
</form>

and a link like:

<div onclick="document.foobar.submit();">click me</div>

How can I capture the submit() method and call my validate function?

JsBin example

Answer by Sushil

You can call method from html itself. modified jsbin. Instead of submitting form on click you can call submitHandler and pass form reference.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
  <script type="text/javascript">
    function validate(){

    }

    function submitHandler(form){
      validate();
      alert('foo');

}
    window.onload = function(){
        document.foobar.submit = submitHandler;
    }
</script>

</head>
<body>
    <form method="POST" action="page.html" onsubmit="submitHandler(this);" name="foobar">
      <input type="text" />
    </form>

    <div onclick="document.foobar.submit()">click me</div>
</body>    
</html>

Answer by Starx

Uniquely identify your form with an id

document.getElementById('formid').onsubmit = function() {
    // You have captured the submit method now do what you need
};

Demo

March 26, 2012

Check if AJAX loaded form contain a submit button

Question by Merianos Nikos

Is there a way to check if the form that has been loaded with AJAX contain a submit button with jQuery ?

Answer by Darin Dimitrov

success: function(content) {
    $('#someplaceholder').html(content);
    var containsSubmitButton = $(':submit', content).length > 0;
}

Answer by Starx

You can do it as this

$("#div").load("yourpage", function() {
    if($("#div").find(":submit").length > 0) {
          console.log("yes");
    }
});
...

Please fill the form - I will response as fast as I can!