sunlock
sunlock

Reputation: 322

How do I catch a form submit in Javascript onload?

I have a 3rd party system, where I can add articles (with (raw) html). One page contains a search form, which does a post to itself. Upon load (after post) it will add a javascript submit form using javascript - e.g.

function redir() {
   document.myform.submit();
}
.... //some other stuff here
redir();

I'll not go into details on the design (I know why it is designed this way but cannot change it - its crappy design, I know!).

Is there someway to catch this "onload" submit?

I have tried this:

var sform = document.getElementsByName('myform');
try {
    sform.addEventListener("submit", alert('Gotcha!'));
} catch(e) {
    sform.attachEvent("submit", alert('Gotcha!')); //Internet Explorer
}

Also jQuery:

$('myform').submit(function() {
    alert('Gotcha!');
    return false;
});

I cannot seem to catch the event. I can override the method:

redir = function(){
    //Empty - override
}

...but the submit action is trigged before my script is loaded or it will override my overridding method.

I hope this makes sense.

Upvotes: 1

Views: 2155

Answers (2)

andyb
andyb

Reputation: 43823

Did you override the function in the correct place? The following works for me and stops the submit.

function redir() {
    document.myform.submit();
}

redir = function(){}

redir();

Demo

Upvotes: 0

Craig M
Craig M

Reputation: 5628

Your jQuery was close. You just need to use a # before your id based selector, just like in CSS.

$('#myform').submit(function() {
    alert('Gotcha!');
    return false;
});

Upvotes: 3

Related Questions