PDA

View Full Version : How to override onsubmit for custom validation


ltwinnerr
08-02-2011, 09:44 PM
I want to override the onsubmit attribute of the form on the newthread page as I have added a few custom fields to it that I need to validate. However the onsubmit value will not change. Here's what I am doing -

var form = document.getElementsByTagName("form")[1];
form.onsubmit = 'override_submit()';

And nothing changes. However if I try to change the action attribute of the form it works no problem.
form.action= 'xyz';


So any ideas on what I am doing wrong?

kh99
08-02-2011, 10:45 PM
I'm not a js expert but it looks OK to me. How do you know it's not changing?

ETA: actually (after googling for answers), if you set it from js you might have to set it to a function and not a string.

So you'd want:

form.onsubmit = override_submit;

ltwinnerr
08-02-2011, 11:33 PM
I've just tried that and it doesnt work either. I cant understand how the action attribute can be changed no problem yet the onsubmit attribute cant.

Can someone try adding the javascript
var form = document.getElementsByTagName("form")[1];
form.onsubmit = override_submit;

to their newthread.php page and see if they can override the submit handler. Because this has me stumped.

kh99
08-02-2011, 11:40 PM
I made this as a test and it works:

<html><head><title>Test</title> </head>
<body>
<form>
<input type="submit">
</form>

<script>
function override_submit()
{
alert("It works!!");
}
var form = document.getElementsByTagName("form")[0];
form.onsubmit = override_submit;
</script>
</body>
</html>


I used [0] instead of [1], but I thought maybe you used 1 because there was another form on the page.

ltwinnerr
08-03-2011, 12:01 AM
Hi, I tried your test and it worked and then I noticed that even though it works the html view in firebug still shows the onsubmit function as the original function...

So I tried it again with vbulletin and it is calling the new function now, even tho firebug still shows the form's onsubmit as the old function. Dont kno if this is a bug with firebug but at least this is working now.

Cheers mate.

--------------- Added 1312334345 at 1312334345 ---------------

Hmmm, one other thing...I need to declare the onsubmit in the form of
onsubmit = 'return override_submit';
So that I can stop the form from getting sent if the validation fails.


But it doesn't work when I use -- return -- and quotation marks.

Any ideas?