views:

43

answers:

2

Hi there !

I have something like this HTML structure :

   <form name="myvalue" id="hello">
      <input type="text" name="name" />
    </form>

I'd like to retrieve the form's name attribute in Javascript, with a cross browser solution.

Obviously,

document.getElementById("hello").name 

won't work because it will return the corresponding input object.

Under chrome, following code works, but I didn't succeeded to find the equivalent for Internet Explorer 8

document.getElementById("hello").getAttribute("name")

Thanks in advance !

Frédéric

+3  A: 

I think this oughtta work

document.getElementById("hello").attributes["name"].value;

tests ok in IE8, which is all I have. you might have to do some browser checking and pick your approach as needed.

edits: actually, your example works fine for me in IE8 too. but not ie7.

lincolnk
ooh neat, didn't realize `attributes` had named properties.
no
This solved the problem !
Frédéric
I'll try this on IE 7 though ;-)
Frédéric
A: 

Try this:

function getFormName (formElement) {
  if (!formElement) return;
  var a=formElement.attributes;
  for (var i=a.length; i--;) {
    if (a[i].name=='name') return a[i].value;
  }
}

Not sure if it will work in IE. Should work everywhere else.

no