views:

340

answers:

4

Given the form below:

<form id="myForm" action="index.php">
    <input type="hidden" name="action" value="list" />
    <input type="submit" />
</form>

How can I get the value for the action property of the form (index.php) using IE6?

Hint: I have tried

document.getElementById('myForm').action

and

document.getElementById('myForm').getAttribute('action')

But neither of them work. They both return the input field (document.getElementById('myForm').action.value == 'list').

+2  A: 

There isn't a simple way.

The presence of the action field, clobbers the action property of the form and getAttribute is broken in IE < 8.

The only way I can think of is to get dirty with regular expressions. I would very strongly suggest changing the form to use a different name for the field than 'action' if at all possible instead.

var form = document.forms.myForm;
var action = form.getAttribute('action');
if (action === form.elements.action) {
       // getAttribute broken;
       var string = form.outerHTML;
       return string.match(/action=(.*?)[> ]/)[1];
} else {
       return action;
}

That regular expression might not be robust enough. So test it hard if you do use it.

David Dorward
+3  A: 

David's right. Here's a less nasty way than the regex though:

var action= document.forms.myForm.cloneNode(false).action;

(Because the clone is shallow, there is no ‘input name="action"’ inside the new form element to confuse it.)

bobince
That's clever. I like it.
David Dorward
A: 

I've just found another way: using or cloning the readAttribtue method available in prototypejs.

Tom
+1  A: 

There is a simple way, using the node's attributes collection:

document.getElementById("myForm").attributes["action"].value

Test page to try it out (also demonstrates the brokenness of getAttribute as mentioned David Dorward's answer):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html lang="en">
<head>
<title>Form Action Access</title>
<script type="text/javascript">
function dotAccess()
{
    alert(document.getElementById("myForm").action.value);
}
function getAttributeAccess()
{
    alert(document.getElementById("myForm").getAttribute("action"));
}
function attributesAccess()
{
    alert(document.getElementById("myForm").attributes["action"].value);
}
</script>
</head>
<body>
<form id="myForm" action="foo">
  <input type="hidden" name="action" value="bar">
  <input type="button" onclick="dotAccess()" value="form.action">
  <input type="button" onclick="getAttributeAccess()" value='form.getAttribute("action")'>
  <input type="button" onclick="attributesAccess()" value='form.attributes["action"]'>
</form>
</body>
</html>
insin
Now that's how an answer should look like! "Here are your options" and "here's what I've found" Thank you.
Tom