Rick Sibley
Rick Sibley

Reputation: 625

Javascript onSubmit not returning false

I'm having an issue with my onsubmit code. I'm using a calculator from a third party company and I am trying to trigger some javascript when the form is submitted. The alert will fire off but if I have the return set to false the form still submits.

Here is the line of code I am working with in my own environment: document.getElementsByTagName("Form")[3].onsubmit = function () { alert('Test'); return false; };

I have built a replica here: (For what ever reason it wont load in the snippet, I copied the same code to my server and it works fine, so here is it in action. Page)

function myFunction() {
  document.getElementsByTagName("Form")[0].onsubmit = function () { alert('Test'); return false; };
}
<button onclick="myFunction()">Wait for script to load then press this button to add the onsubmit, then you can press calculate</button>
<script src="https://calculators.symmetry.com/widget/js/salary.js?key=RHA0Slc2ZjEydjNkR0Y2eTEvOUxpZz09"></script>

I haven't figured out how to do an onload detection for a script yet so that's why you have to wait for the script to load then press the button to insert the javascript.

Thanks for any help.

Upvotes: 0

Views: 143

Answers (1)

ymz
ymz

Reputation: 6914

Well.. in your solution you are adding a new event handler to the form on every button click

Instead of declaring the event handler on page load and then trigger it

It should be....

<script>
    function onMyPageLoaded()
    {
         document.getElementsByTagName("Form")[0].onsubmit = function (e) 
         { 
              e.preventDefault();

              // place your code here

              return false; // cancel form submit
         };
    }

    function doSomething() // use this ONLY if you intend to by-pass the native submit mechanism
    {
      document.getElementsByTagName("Form")[0].submit(); // trigger the event here
    }
</script>

<body onload="onMyPageLoaded()">
    <form>
        <button type="submit">send</button>
    </form>
</body>

Upvotes: 1

Related Questions