Here's the form:
<form name=fname ...
<input name=iname value="" ...
This javascript function obtains the value of the input with:
var val = document.fname.iname.value;
Is that legit? I thought you had to do this with getElementsByName. It works, it's just I've never seen anyone do it that way. Is this one of those things that just happens to work... for now?
UPDATE
According to WHATWG 6.2.4 Named access on the Window object
The Window object supports named properties. The supported property names of a Window object window at any moment consist of the following,...for all applet, embed, form, frameset, img, and object elements...
According to W3C DOM 2 HTML Specification 2.7.2.1 HTMLAllCollection
The following elements name attribute can be referenced as a property of the document object:
anchor, applet, button, form, frame, iframe, img, input, map, meta, object, param, select, and textarea
This referencing approach is standard, but it's use is generally discouraged. A few reasons to avoid directly referencing DOM property or window object by name attributes are: variable shadowing, inadvertently scoping to the window object, major browser inconsistencies, etc. For details on why it should be avoided, read this section and this post.
This Snippet shows a stable and standard way of using form names as a reference document.forms and the referencing form names previously mentioned as well.
SNIPPET
var val1 = document.forms.fname.elements.iname.value;
console.log(val1);
var val2 = fname.iname.value;
console.log(val2);
<form name='fname'>
<input name='iname' value="42">
</form>
Related
I want to access input field value as simple as possible from JavaScript.
<form name="F">
<input name="searchTxt" type="text" id="searchTxt">
</form>
I can access the value with following method (tested on Firefox debugger):
document.F.searchTxt.value
But I found this method is a dialect from Internet Explorer (and works on most browsers for compatibility), and it is obsoleted on W3C DOM.
(reference: Using the W3C DOM - Archive of obsolete content | MDN )
Another way I found is using forms and elements attributes with its child's name:
document.forms.F.elements.searchTxt.value
I like this method and I feel it is simple because it doesn't require any parentheses or quotes but only dots in the statement.
(reference: Obtaining References to Forms and Form Elements in JavaScript - Dynamic Web Coding )
I think the secret of this method is the form has its name (instead of or additional to id), so it can be accessed by its simple name.
Please tell me more simple, more stable or the best method to access the field values.
You can use document.querySelector to access the form's DOM element and it has all the properties that you need:
const form = document.querySelector('form');
console.log(form.elements.searchTxt.value);
let searchTxt= document.forms["F"]["searchTxt"].value;
I have this javascript function:
function clearDiv(div_id) {
alert(div_id);
$(div_id).empty();
}
And the following html:
<input value="Clear" type="button" onClick="clearDiv(div_to_clear)" />
<div id="div_to_clear">
<!-- more html -->
</div>
Why is it that the above will actually find the javascript div object with id div_to_clear and use the $ selector to access it?
If I had done the input as :
<input value="Clear" type="button" onClick="clearDiv('div_to_clear')" />
I would need to change my function to
function clearDiv(div_id) {
alert(div_id);
$('#' + div_id).empty();
}
Is there any documentation about this? Are there advantages to using one method or the other?
IE (and Chrome in an effort for compatability) will create properties on the window with names of elements with ids, corresponding to those elements.
In the first example are are passing window.div_to_clear which points to your element directly. In the second, you are passing a string telling jQuery which element to select.
The first one is non-standard behavior so you should not rely on it.
The first one is actually a browser bug (they called it a feature) to access the DOM node by window.div_to_clear (the global variable) - and jQuery creates its wrapper around the element. For legacy reasons, it still exists in current browsers, but is deprecated. Your really should use the selector solution.
This is because there is a widely-implemented (although not best practice) method by browsers to automatically place html elements with id's into their correlating variable name. For example:
<div id="someId"></div>
will end up psuedo creating the variable someId which holds that html element.
These questions have similar information on the behavior:
Do DOM tree elements with ids become global variables?
Where does the variable holding an element with an id get stored?
Element accessible with ID
Here is a jsperformance test showing that accessing the id in that manner is slower than using document.getElementById: http://jsperf.com/global-id-vs-document-getelementbyid
Consider this HTML:
<form id="MyForm">
<input name="Input1"/>
</form>
To get the form, I would do this:
var form = document.getElementById("MyForm");
Now I know that to get Input1 from the form I can do this:
var input1 = form.Input1;
Can you give me the code for another way to access any form control from a form, by using the name attribute?
I would imagine that a possible answer could involve recursing through descendants of the form and checking for a control with the attribute named "name", with the value "Input1".
Please provide an answer that does not require additional libraries.
The following is not important
In case you're wondering why I'm asking this: I'm using software called Script#, which compiles C# into JavaScript. The current version of Script# doesn't support [form element].[name attribute value], so I'm looking for an alternative way to do this.
You could give the document.getElementsByName function a shot.
An alternative you might be able to use is:
document.getElementById("MyForm")["Input1"]
Either that, or you need to assign an ID directly to the form element, and reference that. Otherwise, multiple forms may contain an element of the same name, and without including the form as part of the reference, you'd have an ambiguity.
I have a question about DOM objects.
What I have learned is that everything in a document are objects?
<form name="myform" action="script.js">
<input type="text">type something</input>
</form>
If we look at the example, is form an object with properties name and action?
But are name and action themselves also objects? i don't quite understand the difference between objects and properties.
And what is the difference between object element and node?
I know basics of html, css, javascript and dom. but can someone describe the big picture for me here how these parts are communicating with each other.
because there are so many elements, properties and methods. so im all lost
Seems to me your trouble is not understanding the concept behind object-oriented programming. JavaScript is an object-oriented language. You should probably take a quick tour of the concepts.
Briefly, though, objects are a way to encapsulate both data (the "properties" you are referring to) and functionality (the "methods" or "functions" you can ask an object to perform).
In the case of the JavaScript DOM, there is a tree of objects, where each object contains properties that are, themselves, objects. So you can have a Form object with methods like onSubmit() and properties like "elements", which is an array of form fields. Each element in the array is another object, like perhaps a TextField object or a Checkbox.
So now you know about objects. One thing about objects is that they can inherit properties from a parent class of object. For example, in JavaScript, there is an Element class and each of the form field objects is an instance of a "subclass" of the Element class. So, since Element defines the "name" property, and TextField and Checkbox and all their friends inherit from Element, they all automatically have this "name" property available too.
The term "node" refers to a particular location in a tree or graph structure. In this case, the DOM (Document Object Model) defines the types of objects that are allowed to be nodes in the tree that represents the webpage. For each webpage you visit, the browser constructs a "DOM tree", which is a big tree of objects representing each of the elements in the webpage.
Notice that HTML is naturally in a tree-like structure: the html tag contains head and body, the head tag contains title, meta, and script tags, the meta tag contains attributes like name and content. All this is arranged by the browser into a tree of objects, and that is what you are manipulating when you use JavaScript to do DOM programming.
So to recap: objects are the fundamental representation of data and functionality in JavaScript. Elements are particular classes of object that are subclasses of the "Element" class, and which represent some kind of form field. These can be found in the form.elements array, which is a property of the form object. Finally, nodes are points in the tree of tags, text, script, and other objects that make up a webpage.
Hope it helps!
I've taught people about the DOM before and found that seeing the DOM in action.
Go get firebug, if you don't have it.
http://getfirebug.com/
After you of course restart Firefox...
Open up any web page and right-click on something, there will be an option called "Inspect Element". This will display the rendered code of the page. When I say rendered I'm referring to the page after it has been modified by any javascript, different from the standard source code which is just the straight HTML sent from the server.
The element which you are inspecting will be highlighted. Now, right click on that highlighted element and select "Inspect in DOM Tab".
Once you're in the DOM tab, this shows you all of the properties of the element you inspected. In here you may see attributes of the element like type="input", methods of the element like focus(), maybe custom prototypes, Firefox proprietary attributes, and much much more.
Here are some methods, functions, and attributes on your need to know list, look these up in the Mozilla Developer Center. Spend some time writing scripts which move you around the DOM and allow you to alter it using these, don't use innerHTML to do anything.
createElement
createTextNode
appendChild
insertBefore
removeChild
cloneNode
setAttribute
removeAttribute
getElementById
getElementsByTagName
childNodes
firstChild
lastChild
nextSibling
hasChildNodes
tagName
attachEvent (IE) / addEventListener (all others)
detachEvent (IE) / removeEventListener (all others)
HTML attributes are exposed as
properties on the element object.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html
http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614
Element = object, property = attribute. A method is just an invocable property, eg onclick.
<form
onsubmit="alert('hi');"
id="contact-form"
>
onsubmit is a method, id is a property, form is a node with a node type of 1 which means it's an HTMLElement and inherits generic HTML properties.
in your example, the name and action are attributes of the form object.
if you had something like this in a JSP page
<form name="frm" action="somepage.jsp" onSubmit=" return validateForm();">
<input type="text" name="txtField" id="txtField"></input>
<input type="submit" value="submit"></input>
</form>
and a js function defined like so that checks to see if any text was entered into a text box.
<script>
function validateForm(){
if(document.frm.txtField.value="")
return false;
else
return true;
}
</script>
you can use the document object to access the form object in the dom and from that access the input element held by the form.
Im working on a form and getting null or not an object errors in ie.
<form action="#" method="post" name="adv_search">
<input class="inputbox" type="text" name="keyword1" value="none" id="keyword1"/>
</form>
<script>
document.adv_search.keyword1.focus();
document.adv_search.keyword1.select();
</script>
//whereas if I use
<script>
var key1 = document.getElementById('keyword1');
key1.focus();
key1.select();
</script>
//everything is fine
i would like to understand why.
i would like it to work without having the id tag for the input field
thanks in advance
shouldnt the document.formname.fieldname.focus();
and document.formname.fieldname.select();
work?
Your particular example works for me, but if I add another field with the same name:
<input type="text" name="keyword1" />
<input type="text" name="keyword1" />
Then document.adv_search.keyword1.focus() will fail with the error you specify.
The reason is that:
document.adv_search.keyword1
is a shortcut for this syntax (which goes back to DOM Level 0 and the Netscape 2 days!):
document.forms.adv_search.elements.keyword1
(Incidentally, it is better to use this full syntax, instead of relying on the behaviour of the ‘document’ and ‘form’ objects being indexed on names: if a new method is added to HTMLDocument or HTMLFormElement, that might clash with the control name you are using. This is less of an issue when you use the document.forms or form.elements collections. Also, IE mistakenly dumps all names and ids into ‘document’, so if you've got an element with id="adv_search" in addition to the form with that as a name, document.adv_search will return the wrong one.)
Anyway, the DOM Level 0 scripting methods behave slightly curiously when you access an element by name like this. If there is a single matching element, you'll get that one as a standalone object. If, on the other hand, there are more than one, you'll get a list of objects. You can't call focus() or select() on an array-like list, which is why the error appears; you'd have to do something like keyword1[0].focus() when the list was returned.
So you have to decide whether you're going to be using old-school DOM Level 0 methods to access your form controls — in which case you're going to have to cope with sniffing for single-or-multiple-controls — or move to the ID-based methods introduced by ‘DOM Level 1’:
document.getElementById('keyword1').focus();
The ID-based methods are generally a bit more typing (in the script and to add ‘id’s to all elements you wish to access this way, if they don't already have them), but they are simple and unambiguous. (Also you can then drop the name on the <form> itself.)
The ID approach really is best but if you want to go by name, use getElementsByName.
In this case, it might look like this:
<script>
// retrieves array of objects with the name 'keyword1'
// and takes the first one
var key1 = document.getElementsByName('keyword1')[0];
key1.focus();
key1.select();
</script>