Forum Moderators: open

Message Too Old, No Replies

Running an onsubmit function without markup in my html

         

ntbgl

12:30 am on Feb 18, 2009 (gmt 0)

10+ Year Member



I am trying to keep my html free of javascript markup, while at the same time trying to make a script run when a user presses a submit button my my form.

Right now I'm just trying to get my script to run, using an alert box to test.

This is in my head:

<script type="text/javascript">
window.onload=function(){
window.onsubmit=function(){
alert("hi");
return false;}}
</script>

And this is in my body:

<form action="/" method="post">
<div><input type="submit" /></div>
</form>

Kings on steeds

2:07 am on Feb 18, 2009 (gmt 0)

10+ Year Member



you need to attach the onSubmit to your form

<script>
document.forms[myForm].onSubmit = function(){ alert('hi'); }
</script>

<form name='myForm' method='post'>
<input type='submit' value='send'>
</form>

untested, but something like this should work...

ntbgl

5:37 am on Feb 18, 2009 (gmt 0)

10+ Year Member



Thanks for the reply. I tried it, but I still wasn't able to get it to run. I even tried ...forms["myForm"]... but to no avail.

Fotiman

3:38 pm on Feb 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




<script type="text/javascript">
window.onload = function () {
document.forms.myForm.onsubmit = function () {
alert("hi");
return false;
}
}
</script>

rocknbil

3:46 pm on Feb 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You don't submit a window, you submit a form. :-)

Additionally let me add, you should be referencing your objects by ID, not by name, it's just an easier method of accessing document objects and a better habit to form.


<script type="text/javascript">
if (document.getElementById) {
window.onload=function() {
document.getElementById('my-form').onsubmit=function(){
alert("hi");
return false;
}
}
}
</script>
<form action="/" id="my-form" method="post">
<div><input type="submit" id="submitButton" value="Submit"></div>
</form>

<snicker> Fotiman is too quick once again. :-)

Fotiman

5:36 pm on Feb 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I was going to suggest adding an id to the form and using getElementById, but I was in a rush when I posted my suggestion. :-)