Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

FAQ Topic - How do I get the value of a form control? (2012-05-20)

2 views
Skip to first unread message

FAQ server

unread,
May 19, 2012, 7:00:03 PM5/19/12
to
-----------------------------------------------------------------------
FAQ Topic - How do I get the value of a form control?
-----------------------------------------------------------------------

In HTML documents, a form may be referred to as a property of the
`document.forms` collection, either by its ordinal index or by name
(if the `form` has a name). A `form`'s controls may be similarly referenced
from its `elements` collection:

var frm = document.forms[0];
var control = frm.elements["elementname"];

Once a reference to a control is obtained, its (string) `value`
property can be read:-

var value = control.value;
value = +control.value; //string to number.

Some exceptions would be:

First Exception: Where the control is a `SELECT` element, and
support for older browsers, such as NN4, is required:

var value = control.options[control.selectedIndex].value;

Second Exception: Where several controls share the same name,
such as radio buttons. These are made available as collections
and require additional handling. For more information, see:-

<URL: http://jibbering.com/faq/notes/form-access/>
Unsafe Names for HTML Form Controls [ref 1]

Third Exception: File inputs. Most current browsers do not allow
reading of `type="file"` input elements in a way that is useful.

References:
-----------

[1] http://jibbering.com/faq/names/


The complete comp.lang.javascript FAQ is at
http://jibbering.com/faq/

--

The sendings of these daily posts are proficiently hosted
by http://www.pair.com.

Evertjan.

unread,
May 20, 2012, 4:15:57 AM5/20/12
to
FAQ server wrote on 20 mei 2012 in comp.lang.javascript:

> var value = control.value;
> value = +control.value; //string to number.
>
> Some exceptions would be:
>
> First Exception: Where the control is a `SELECT` element, and
> support for older browsers, such as NN4, is required:
>
> var value = control.options[control.selectedIndex].value;

This is nice, I don't support NN4.

However you cannot write to this select value,
so you still need selectedIndex for setting the option:

Example:

============================
<select onchange='
document.getElementById("s").innerHTML=this.value;
this.selectedIndex=0;
'>
<option>--</option>
<option value=a>a</option>
<option value=b>b</option>
<option value=c>c</option>
<option value=d>d</option>
</select>
<span id=s>--</span>
============================


btw, it seems that IE9 still does not support the defaulting:

<option>a</option>

but needs:

<option value=a>a</option>


--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
0 new messages