简体   繁体   中英

Form onsubmit doesn't work with form .submit()

I have a form and I have applied a function onsubmit:

var theForm = document.getElementById("myform");
theForm.onsubmit = function FormSubmit() {
alert("something");
};

I have added in my form a submit button <input type="submit" value="submit"/>

The something text is alerted. Great!

I have an image and I want to make it to submit the form:

<img onclick="document.getElementById('myform').submit();" src="mylocation"/>

But it doesn't make the function... it doesn't alert something on screen.

EDIT: I don't want something with jQuery. Pure JS

Event handlers are only run in response to user actions or asynchronous events, not normal program actions like calling form.submit() . One reason for this is that it's not uncommon for the submit handler of a form to do some work and then call form.submit() , and this would cause an infinite recursion if it triggered the handler again.

Put the code you want to run in a named function:

function mySubmit() {
    alert("something");
}

theForm.onsubmit = function() {
    mySubmit();
};

Then you can call that function in your click handler:

<img onclick="mySubmit(); document.getElementById('myform').submit();" src="mylocation"/>

The problem is event handlers doesn't respond when the event called by script.

Say like bellow

  var theForm = document.getElementById("myform");
  function FormSubmit() {
    alert("something");
  };
  theForm.onsubmit = FormSubmit;

And call manually the function onclick of image like bellow

<img onclick="FormSubmit();document.getElementById('myform').submit();" src="mylocation"/>

You can use an a tag around your image, something like this:

<a href="javascript://" onClick="document.getElementById('myform').submit();">
  <img src="mylocation" />
</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM