0

I want to add some logic before form submission. it's work when i click on submit button. but there is another button which submit the form via JavaScript and my logic doesn't call on that. below is the snippet for reference.

<form action="text" method="get">
     <input type="submit">
</form> 
<script>
    document.forms[0].onsubmit = function(){
        alert('hi');
    };
    //document.forms[0].submit();
</script>

when i manually click on submit button, alert comes. but after un-commenting the second line document.forms[0].submit(); nothing comes.

It'll be also helpful to get explanation for this behavior. as i understand submit handler should be trigger on both cases.

any help will be much appreciated.`

kp singh
  • 1,430
  • 8
  • 21
  • possible duplicate of [Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?](http://stackoverflow.com/questions/645555/should-jquerys-form-submit-not-trigger-onsubmit-within-the-form-tag) – suvroc Aug 10 '15 at 09:48
  • Well detailed answer is given on this link : http://stackoverflow.com/questions/19847203/form-onsubmit-not-getting-called – Juned Lanja Aug 10 '15 at 09:52

2 Answers2

0

you need to stop the default action, you can do this with event.preventDefault();

document.forms[0].onsubmit = function(event){
    event.preventDefault();
    alert('hi');
};
BrendanMullins
  • 587
  • 3
  • 18
0

Use the click event instead.

document.forms[0].getElementsByTagName('input')[0].click();
Md Ashaduzzaman
  • 4,032
  • 2
  • 18
  • 34