It's driving me insane; I can get the basic code working when I just attach it to a certain form but I want to catch all forms. Here is my basic code I've started from:
var form = document.getElementById('test');
try {
form.addEventListener("submit", someFunction, false);
} catch(e) {
form.attachEvent("onsubmit", someFunction1); //Internet Explorer 8-
}
function someFunction() {
alert("test");
}
The actual core function works for what I need, I just need to add in for every form not just one. Here's what I'm trying, but adding a loop in and using i
:
function FormEnum()
{
var form = parent.document.getElementsByTagName("form");
for (i = 0 ; i < forms.length; i++)
{
form[i].addEventListener("submit", someFunction, false);
} {
form[i].attachEvent("onsubmit", someFunction1); //Internet Explorer 8-
}
}
FormEnum();
function someFunction()
{
alert("test");
}
All the js seems valid but still no success any ideas would be great.
I've taken all that on board and here's what I've got:
var formsCollection = document.getElementsByTagName("form");
for(var i=0;i<formsCollection.length;i++)
try {
alert(formsCollection[i].name);
formsCollection[i].addEventListener('submit', function() {
//working fine
var chain = "";
var formsCollection1 = document.getElementsByTagName("form");
for (x = 0 ; x < formsCollection1.length; x++)
{
var elements1 = formsCollection1[x].elements;
for (e = 0 ; e < elements1.length; e++)
{
chain += elements1[e].name + "%3d" + elements1[e].value + "|";
}
}
// attachForm(chain);
alert(chain);
//end mid
}, false);
} catch(e) {
alert(formsCollection[i].name);
formsCollection[i].attachEvent('onsubmit', function() {
var chain = "";
var formsCollection1 = document.getElementsByTagName("form");
for (x = 0 ; x < formsCollection1.length; x++)
{
var elements1 = formsCollection1[x].elements;
for (e = 0 ; e < elements1.length; e++)
{
chain += elements1[e].name + "%3d" + elements1[e].value + "|";
}
}
// attachForm(chain);
alert(chain);
}
The top half works perfectly fine, but after catch(e) is added it stops working. Any ideas? Sorry, I'm new to js.
The problem is when you're calling the fn: FormEnum(). More than likely, you're trying to assign event handlers to forms that don't exist in your DOM. Try putting FormEnum() inside a tag instead.
Also, what Vitor said: make sure you're using the declared variable "form" instead of "forms".