Thanks...
Bruce
I could find nothing on retrieving a radio button value without a form
object. So, I added a form object.
Thanks for the help.. Life is good!!
Bruce
Get a reference to the element some other way, e.g. assign an ID and
use document.getElementById:
<input type="text" id="input0">
<button onclick="
alert(document.getElementById('input0').value);
">Show value</button>
--
Rob
<script type="text/javascript">
function ff() {
var f = document.forms[0];
if(f) f = f.un;
else f = document.getElementsByName('un');
if(!f) {
f = [];
var r = document.getElementsByTagName('INPUT');
for(var i=0, n=r.length; i<n; i++)
if(r[i].name == 'un') f.push(r[i]);
}
alert(f[1].value);
}
</script>
</head>
<body>
<p>un: <input type="radio" name="un" value="1">
<p>deux: <input type="radio" name="un" value="2">
<p>trois: <input type="radio" name="un" value="3">
<p><button onclick="ff()">voir/see</button>
--
Stéphane Moriaux avec/with iMac-intel
Yes, this works great with a "type=text" but I my type is "radio".
How can I do this with a radio button?
Thanks for the comeback..
Bruce
<html>
<head>
<script type="text/javascript">
function getValue(t)
{
var x=document.getElementById(t.id);
alert(t.id + ' ' + t.value);
}
</script>
</head>
<body>
<input id="radio" name="radio" type="radio" value="a"
onclick="getValue(this)">a
<input id="radio" name="radio" type="radio" value="b"
onclick="getValue(this)">b
</body>
</html>
--
Luuk
Thanks!! I like it!! Never heard of getElementByTagName. I guess I'll
have to look for others like it..
Bruce
>How can I retrieve a radio button value when I am NOT using a form?
>There are many, many examples when a form is used but I'm NOT using a
>form?
You obtain a reference to the radiobutton (which will be one of a set),
then you test its checked property.
If you have a reference to any object in the document, including the
body, you can walk the DOM tree until you reach the button. Otherwise,
if that is not convenient, use document.getElementById().
This rudimentary demo works :
<body>
<input type=radio name=A ID=Z>
<input type=radio name=A checked>
<input type=button
onClick="this.value=document.getElementById('Z').checked">
</body>
This question would be better answered by reference to a section that I
have said that the FAQ should contain : "How do I get a reference to an
element of my page?". Several existing sections could then start with
"Get a reference to the ***; _see FAQ x.y_.". The new section would
indicate ALL of the distinct ways of getting a reference to a stated
element.
--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (RFCs 5536/7)
Do not Mail News to me. Before a reply, quote with ">" or "> " (RFCs 5536/7)
That line is redundant, x and t will reference exactly the same DOM
element.
> alert(t.id + ' ' + t.value);
> }
> </script>
> </head>
> <body>
>
> <input id="radio" name="radio" type="radio" value="a"
> onclick="getValue(this)">a
> <input id="radio" name="radio" type="radio" value="b"
> onclick="getValue(this)">b
A general solution for getting the value of the checked radio button
would be to call the following function and pass it the name of the
radio button set:
funcion getValue(buttonSetName) {
var buttons = document.getElementsByName(buttonSetName);
var i = buttons.length;
while (i--) {
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
Noting that one of the buttons should always be checked.
See also:
<URL: http://www.jibbering.com/faq/notes/form-access/#faBut >
--
Rob
<FAQENTRY>
> This question would be better answered by reference to a section that I
> have said that the FAQ should contain : "How do I get a reference to an
> element of my page?". Several existing sections could then start with
> "Get a reference to the ***; _see FAQ x.y_.". The new section would
> indicate ALL of the distinct ways of getting a reference to a stated
> element.
I agree. There is a section in the notes on accessing form controls
that could be expanded and modified to suit:
<URL: http://www.jibbering.com/faq/notes/ >
Section 9 of the FAQ, "DOM and Forms", includes the following
subsections:
9.4 Why are my rollovers so slow?
9.5 How do I disable the right mouse button?
9.6 How do I detect Opera/Safari/IE?
9.9 How can I see in javascript if a web browser accepts cookies?
Those subsections are not about the DOM or forms. Either they should
be moved to a suitable section or section 9 be renamed to more
accurately indicate its content.
</FAQENTRY>
--
Rob
i dont see that info there....?
>
>
> --
> Rob
But i found it here:
http://www.w3.org/TR/html401/interact/forms.html
chapter 17.2.1
<quoot>
radio buttons
Radio buttons are like checkboxes except that when several share the
same control name, they are mutually exclusive: when one is switched
"on", all others with the same name are switched "off". The INPUT
element is used to create a radio button control.
If no radio button in a set sharing the same control name is initially
"on", user agent behavior for choosing which control is initially "on"
is undefined. Note. Since existing implementations handle this case
differently, the current specification differs from RFC 1866 ([RFC1866]
section 8.1.2.4), which states:
At all times, exactly one of the radio buttons in a set is checked. If
none of the <INPUT> elements of a set of radio buttons specifies
`CHECKED', then the user agent must check the first radio button of the
set initially.
Since user agent behavior differs, authors should ensure that in each
set of radio buttons that one is initially "on".
</quoot>
I like the part that says:
"the current specification differs from RFC 1866"
--
Luuk
document.getElementById(button_id).checked (is the button selected)
document.getElementById(button_id).value (the assigned value)
Values are assigned to buttons with the value attribute. The assigned
value of the selected button in a radio group of name group_name is the
value that is passed back against group_name in a normal form submit.
Rgds
Denis McMahon
use of that 'x' ?
> alert(t.id + ' ' + t.value);
> }
> </script>
> </head>
> <body>
>
> <input id="radio" name="radio" type="radio" value="a"
> onclick="getValue(this)">a
> <input id="radio" name="radio" type="radio" value="b"
> onclick="getValue(this)">b
>
> </body>
> </html>
<html>
<head>
<script type="text/javascript">
function getValue(t)
{
alert('id: '+(t.id? t.id : 'no')+' name: '+(t.name? t.name :'no') +
' value = ' + t.value);
}
</script>
</head>
<body>
<input name="radio" type="radio" value="a" onclick="getValue(this)">a
<input name="radio" type="radio" value="b" onclick="getValue(this)">b
<input name="check" type="checkbox" value="c" onclick="getValue(this)">c
<input id="checkie" type="checkbox" value="d" onclick="getValue(this)">d
</body>
</html>
// an element catched by its ID
document.getElementById('element-id');
with d = document or an element somewhere
// a collection of elements catched by its NAME
// not well supported by every browsers
d.getElementsByName('element-name');
// a collection of elements catched by TAG
d.getElementsByTagName('TAG-NAME'); // better in uppercase
// collection catched by class name (quite new, not with IE)
document.getElementsByClassName('class-name');
<https://developer.mozilla.org/en/DOM/document.getElementsByName>
<http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx>
<https://developer.mozilla.org/en/DOM/document.getElementsByTagName>
<http://msdn.microsoft.com/en-us/library/ms765549%28VS.85%29.aspx>
<https://developer.mozilla.org/fr/DOM/document.getElementsByClassName>
<http://msdn.microsoft.com/en-us/library/ff462057%28VS.85%29.aspx>
oops, a left-over from something else...
the complete line with
"var x=document.getElementById(t.id);"
should not have been there....
--
Luuk
does that solve the problem with radio-buttons out of a form and
*without* id ?
1<input type="radio" name="sam" value="1">
2<input type="radio" name="sam" value="2" checked>
3<input type="radio" name="sam" value="3">
4<input type="radio" name="sam" value="4">
<button onclick="alert(document.sam.value)">
checked radio value (1)</button>
<button onclick="alert(radio('sam'))">
checked radio value (2)</button>
<script type="text/javascript">
function radio(_name) {
var r = document.getElementsByTagName('INPUT'),
n = r.length;
while(n--) if(r[n].name == _name && r[n].checked) return r[n].value;
}
</script>
Try:
alert([x.id == t.id, x === t]);
In the general use of that function, there are other cases by which
identifiers `x` and `t` could possibly reference different objects. For
example, if `t` is an Object object or is an element that is not in the
document (or vice versa). They could also be different objects if the
function runs in older versions of IE due to an ID/NAME bug and the
author has not carefully followed the (somewhat vague) warning in HTML 4
about NAME and IE sharing the same "namespace".
>> alert(t.id + ' ' + t.value);
>> }
>> </script>
>> </head>
>> <body>
>>
>> <input id="radio" name="radio" type="radio" value="a"
>> onclick="getValue(this)">a
>> <input id="radio" name="radio" type="radio" value="b"
>> onclick="getValue(this)">b
>
The markup is invalid.
The `id` attribute must be unique. The TITLE element is missing.
Depending on the DTD, the INPUT might not be allowed to be child of BODY.
The markup should be valid.
<http://jibbering.com/faq/#accessElementBeforeDefined>
--
Garrett
I think a "notes" article on that might be the right choice. If the FAQ
reader is asked the read the FAQ entirely, then it should be terse so
that the reader can find the right part and then go to the "notes".
If the FAQ is highly detailed and specific then it is a little unfair to
impose a barrier to the reader to read the whole FAQ before posting a
question.
Accessing Elements
* _document.getElementById_
* _document.getElementsByName_
* DOM HTML Collections
- document.forms
- document.links
- etc.
The article could probably go on for about 2 pages, starting with high
level overview and then mentioning browser bugs.
> I agree. There is a section in the notes on accessing form controls
> that could be expanded and modified to suit:
>
> <URL: http://www.jibbering.com/faq/notes/>
>
> Section 9 of the FAQ, "DOM and Forms", includes the following
> subsections:
>
> 9.4 Why are my rollovers so slow?
Move to: "Ajax and Server Communication"
> 9.5 How do I disable the right mouse button?
Move to: "Things not to attempt in a browser"?
> 9.6 How do I detect Opera/Safari/IE?
Move to: "Windows and Frames"? or new category?
> 9.9 How can I see in javascript if a web browser accepts cookies?
`document.cookies` is defined in DOM 2 HTML. I think should stay under
"DOM and Forms".
>
> Those subsections are not about the DOM or forms. Either they should
> be moved to a suitable section or section 9 be renamed to more
> accurately indicate its content.
See above.
[...]
--
Garrett
<html>
<body>
<p id="radiosContainer">
1<input type="radio" name="grupo" value="UNO">
2<input type="radio" name="grupo" value="DOS" checked>
3<input type="radio" name="grupo" value="TRES">
</p>
<p>
<button id="which">Which ?</button>
</p>
<script type= "text/javascript">
function $ (id) { return document.getElementById(id) }
radios = $("radiosContainer").getElementsByTagName('input');
$("radiosContainer").onclick= function (e) {
if (e.srcElement.name === "grupo") alert(e.srcElement.value);
};
$("which").onclick= function () {
[].forEach.call(radios, function (e) { if (e.checked)
alert(e.value) });
};
</script>
</body>
</html>
--
Jorge.
$("radiosContainer").onclick = function (e) {
var el = e.target || e.srcElement;
if (el.name === "grupo") alert(el.value);
};
> $("which").onclick= function () {
> [].forEach.call(radios, function (e) { if (e.checked)
> alert(e.value) });
> };
> </script>
> </body>
> </html>
--
Stéphane Moriaux avec/with iMac-intel
Touché :-)
--
Jorge.
Incrível! window.event.scrElement seems to work on Safari !
>
There are a few browsers that have the standard DOM event model as well
as partial support for MSIE event model. Opera, Chrome, Safari, support
IE event model in part and now IE9 will support both, though using a
different strategy than the others.
Some implementations provide additional properties of the event object
that mimic IE properties yet others, notably IE9 beta, provide the DOM
event parameter and then also provide a separate global `window.event`
that is an IE event model event.
To demonstrate this, we can compare the parameter passed to an event
handler with a global `event` property.
Example:
javascript:void(document.onclick=function(ev){alert(ev===event);})
Clicking anywhere in the document, the results are:
Safari 4, Chrome 5, Opera:
true
IE9 pre 4:
false
Firefox:
ReferenceError: event is not defined.
The results show that during the event, in Safari, Chrome, and Opera a
global `event` property is equal to the `ev` parameter. In IE9b4 that a
global event property is not equal to the `ev` param and in Firefox 3.6,
there is no global `event` property.
The IE DOM event model is nonstandard and varies in support. In
contrast, where the DOM event model is implemented, implementations are
more consistent.
Therefore, the most logical approach is to first try to use the DOM
event model.
--
Garrett
Oooops ! Thanks.
(...)
> Therefore, the most logical approach is to first try to use the DOM
> event model.
I think so.
I don't know how you can know and remember all that particularities !
The significance of this observation of IE is questionable when you
consider that traditionally IE has returned a unique event object
instance each time you read - window.event -. That is, given:-
<html>
<head>
</head>
<body>
<input type="button" value="click"
onclick="alert((window.event == window.event));">
</body>
</html>
- clicking on the button in IE (tested on 6, likely true in later
versions) alerts false. This is not an unusual feature of equality
testing applied to event objects as it has been shown that given two
consecutively retrieved references to event objects, expandos added to
one are not visible on the other, and not visible on newly retrieved
event objects latter in the bubbling process (so you cannot use
objects retrieved via - window.event - to pass information between
event handlers).
If the - window.event - reference always evaluates to a new and unique
event object then comparing the result of that reference with any
other object must produce a false result.
Richard.
I forgot about that. IE9 (in IE9 mode) does have different event
objects, though.
There are three ways to attach an event callback via script in IE9 (not
counting event handler attributes): legacy event handler property
assignment, attachEvent, and addEventListener.
In the event handler, the properties for the event parameter vary
depending on how the event was added. A `target` property is absent from
both the global `window.event` and the event parameter passed to the
callback of `attachEvent` but is present in legacy event handler
property and in parameter passed to addEventListener.
The (IE proprietary) `srcElement` property is present no matter how the
callback was added.
IE has implemented DOM Events while preserving behavior of IE's
proprietary event model.
Testing in IE9 pre 4:
function inspectEvent(ev) {
var gEvent = window.event,
result = [];
if (ev) {
result.push('ev.target: '+ev.target,
'ev.srcElement: '+ev.srcElement);
}
if (gEvent) {
result.push("event.target: " + gEvent.target,
"event.srElement: "+ gEvent.srcElement);
}
prompt("", result.join("\n") );
}
document.attachEvent("onclick", inspectEvent);
Result:
ev.target: undefined
ev.srcElement: [object HTMLParagraphElement]
event.target: undefined
event.srElement: [object HTMLParagraphElement]
document.onclick = inspectEvent;
Result:
ev.target: [object HTMLBodyElement]
ev.srcElement: [object HTMLBodyElement]
event.target: undefined
event.srElement: [object HTMLBodyElement]
document.addEventListener("click", inspectEvent, false);
Result:
ev.target: [object HTMLBodyElement]
ev.srcElement: [object HTMLBodyElement]
event.target: undefined
event.srElement: [object HTMLBodyElement]
--
Garrett
I do remember more than I care to, though.
--
Garrett
>> This question would be better answered by reference to a section that I
>> have said that the FAQ should contain : "How do I get a reference to an
>> element of my page?". Several existing sections could then start with
>> "Get a reference to the ***; _see FAQ x.y_.". The new section would
>> indicate ALL of the distinct ways of getting a reference to a stated
>> element.
>
>I agree. There is a section in the notes on accessing form controls
>that could be expanded and modified to suit:
>
><URL: http://www.jibbering.com/faq/notes/ >
I doubt whether many of the target audience read the Notes, turgid and
bloated as they are.
The FAQ should contain something like what SAM wrote, but condensed :
------------
To obtain a reference R to an element, either walk the DOM tree from an
element of known R, or
R = document.getElementById('element-id');
To obtain a reference C to a collation of elements, with d = document or
a reference to another element :
C = d.getElementsByName('element-name');
C = d.getElementsByTagName('tag-name');
C = document.getElementsByClassName('class-name'); // ?? d.get... ??
C = document.anchors
C = document.links
C = document.forms
// AND all others of those general sorts etc.
// Explain also how a C is indexed.
In form element handlers, this.form is a reference to the form.
For details, see the FAQ Notes or <link to readable reference site> and
<link to Standard>.
------------
I am sure that there is more to be said : but, in the FAQ, brevity is
essential.