views:

47

answers:

4

Hopefully this is a pretty simple question! I've got the code working in jQuery to listen for a specific form on a page to be submitted and perform an alert when it is.. I.e.: The form itself doesn't have an ID so I am targeting the form within a specific DIV ID.

$("#content form").submit(function() {
    alert("lorem ipsum dolor?");
});

What would be the syntax for performing this in javascript alone without using jquery? For example, I have this code (below) and just am unsure of how to listen for the form to be submitted to perform an action..

var submitform = document.getElementById("content").getElementsByTagName("form");

Thanks!

+1  A: 
submitform.onSubmit = function() {
    alert("lorem ipsum dolor?");
}
JacobM
Don't forget to add a final semicolon. Moreover, in the OP's question, `getElementsByTagName` returns an array of form elements, not a form element to which you can attach an event handler.
Marcel Korpel
A: 

You can use the unSubmit handler.

Babiker
+4  A: 

To do it in a cross browser, not destructive way, it takes a bit of code:

var submitform = document.getElementById("content").getElementsByTagName("form")[0],
    callback = function(){
       alert("lorem ipsum dolor?");
    };


if(window.addEventListener){
   submitform.addEventListener("submit", callback, false); // Most modern browsers
} else if (window.attachEvent){
   submitform.attachEvent("onsubmit", callback); // IE
} else {
   submitform.onsubmit = callback; // Destroys other handlers
}
Doug Neiner
This is better than mine, because the extra thing that the jQuery version gives you is that it does the right thing if there are already other bindings for this event; the code I gave (and Marcel gave) will overwrite those other bindings. Doug's code, like jQuery's, simply adds your new binding to whichever ones already exist. (Sometimes, of course, either you know your code is the only event handler for that event, or you *want* to replace any existing event handlers.)
JacobM
According to [this rather old article](http://dev.opera.com/articles/view/event-capture-explained/), Opera gets into trouble with event capturing; instead, you should rather use bubbling; the article suggests to set the third parameter to `false`.
Marcel Korpel
@Marcel Thanks for that info, I updated my answer to change it to false!
Doug Neiner
Thanks! This was very helpful. I'm glad I asked because even had I pieced it together on my own I would of forgotten about the cross browser. Again, thanks everyone for the help.
flight643
+1  A: 

First of all, you should known that the getElementsByTagName will return a NodeList, you need to get the first DOM element, e.g.:

var submitForm = document.getElementById("content")
                         .getElementsByTagName("form")[0];

Then you can bind the submit event:

submitForm.onsubmit = function () {
  alert("lorem ipsum dolor?");
};
CMS