Input in the form with the name "action" overrides the action property of the form. This is mistake?

I have a form marked as

<form class="form1" method="post" action="form1.php" style="width:405px"> 

Usually I could access the form action in javascript by accessing the .action of the form object, e.g.

 document.forms[0].action 

which will return the value

 form1.php 

However, if I have an element named "action" as a component of the form, this "action" becomes the content of the form action. That is, if the markup of the form contains, for example,

 <input name="action" type="hidden" value="check" /> 

Then

 document.forms[0].action 

returns value

 <input name="action" type="hidden" value="check" /> 

Now I figured out how to get around this: using

 document.forms[0].getAttribute("action") 

However, this is an unpleasant gotcha that too embarrassed me. This is mistake? Known DOM management issue? Or should I just get used to using .getAttribute ()?

+8
javascript html-form
source share
1 answer

I would not call it a mistake. This effect occurs because attributes can be read using element.attributename , and named inputs inside the form can be accessed in the same way, formelement.inputname . If there is an attribute and 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 read a well-known attribute that has been included in markup or added using setAttribute in JavaScript. For dynamic values, such as, for example, the checked attribute of a checkbox, I do not use getAttribute . But, most likely, this is a matter of personal preference.

+4
source share

All Articles