I have a form marked up as
<form class="form1" method="post" action="form1.php" style="width:405px">
Ordinarily, I could access the action of the form in javascript by referring to the .action
of the form object, for example
document.forms[0].action
which would return the value
form1.php
However, if I have, as a component of the form, an item named "action", this "action" becomes the content of the form's action. That is, if the form markup contains, for example,
<input name="action" type="hidden" value="check" />
Then
document.forms[0].action
returns the value
<input name="action" type="hidden" value="check" />
Now, I did work out how to get around this: by using
document.forms[0].getAttribute("action")
However, it's a nasty gotcha that confused me for too long. Is this a bug? A known gotcha of DOM management? Or should I just get into the habit of using .getAttribute()?
I would not call this a bug. This effect occurs, because attributes can be read by using element.attributename
and named inputs inside a form can be accessed in the same way, formelement.inputname
. If there is an attribute and an input with the same name, there is no guarantee which one will be used. It probably behaves differently in different browsers.
I personally use getAttribute
if I am reading a known attribute that was included in the markup or added using setAttribute
in JavaScript. For dynamic values like, for example, the checked
attribute of a checkbox, I don't use getAttribute
. But this is more a question of personal preference, I guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With