Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form elements with a name attribute that is the same as a form-property, shadow/override the native form-property. Is there a workaround?

If you have an input element in a form with the same name as a form's native property, then that element will shadow the native property.

For example, consider the following form:

<form id = "test">
    <input name="tagName" type="text" />
    <input name="nodeName" type="text" />
</form>

The form element's tagName and nodeName both normally return FORM. But in this case, the following code:

var f = document.getElementById("test");

console.log(f.tagName);
console.log(f.nodeName);
console.log(f["tagName"]);
console.log(f["nodeName"]);

displays:

<input name=​"tagName" type=​"text">​ 
<input name=​"nodeName" type=​"text">​
<input name=​"tagName" type=​"text">​
<input name=​"nodeName" type=​"text">​

Is there a workaround for this (other than renaming the fields)? getAttribute works for things like name, action, or method, but not for properties like nodeName or tagName.

Fiddle here.

Something even more interesting: in this fiddle I'm simply logging the form itself. Normally that would show you the HTML, but now Chrome simply logs TypeError.

like image 894
Vivin Paliath Avatar asked Apr 08 '14 16:04

Vivin Paliath


People also ask

Why should you use form elements instead of custom coding data inputs in JavaScript?

If something is a form, use a form element. This helps assistive devices like screen readers better understand the content of the page and give the person using them more meaningful information.

What is a form specific element?

elements. The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the <form> element. Independently, you can obtain just the number of form controls using the length property.


1 Answers

I can't think of a way of doing it directly on the <form> element. The best I can think of is creating a clone of the element without any descendants and examining the clone's properties:

var clonedForm = f.cloneNode(false);
console.log(clonedForm.nodeName);

UPDATE

As pointed out in the comments, this has the same problem in that cloneNode can be overridden in the same way as nodeName. Since any property of the form can be overridden, this makes it a difficult problem to overcome.

like image 70
Tim Down Avatar answered Sep 29 '22 00:09

Tim Down