Here is my attempt at validating that at least one radio button has been selected.
It does work but if you can improve on it that would be great too, seems like alot of code to do this simple thing. But then again i can understand it too.
How does this look:
Its for a story selection page.
20 items to a page
Code:
<script type="text/javascript">
function pick_story()
{
var rad = document.getElementsByName("pickstory");
if(!rad)
{
alert("Please select a story from the list first");
return (false);
}
var radioLength = rad.length;
if(radioLength != undefined)
{
for(var i = 0; i < radioLength; i++)
{
if(rad[i].checked)
{
var radchecked = 'checked';
}
}//close for
if(radchecked != 'checked')
{
alert("Please select a story from the list first");
return (false);
}
}else{ //undefined
alert("Please select a story from the list first");
return (false);
}//close else
return (true);
}//close function
</script>
If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
* The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".
An alternative (I suspect yours always returns false? but I didn't check this):
Code:
function pick_story() {
var rad = document.getElementsByName("pickstory");
if (rad && rad.length > 0) {
var radLength = rad.length;
for (var i = 0; i < radLength; i++) {
if (rad[i].checked) {
return true;
}
}
alert('You have not checked.');
return false;
} else {
// couldn't get pickstory elements for some reason..
return false;
}
}
A difference here is that it returns as soon as a checked value is found.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Last edited by AndrewGSW; 12-12-2012 at 11:01 PM..
If the radio buttons only exist on a specific form, which has (as it should) an id, then it is more efficient to do this:
Code:
var frm = document.getElementById('formid');
var rad = frm.getElementsByName("pickstory");
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
var rad = document.getElementsByName("pickstory");
if(!rad)
{
alert("Please select a story from the list first");
return (false);
}
The only way rad can be null there is if there are ZERO element on the page with the name "pickstory".
Whether or not any of the elements are radio buttons, whether or not zero or one or whatever of those elements are checked, if even *ONE* by that name exists, rad will not be null, so the if test there is a waste of time.
One good generic way to handle either radio buttons or same-named checkboxes, when you know that at least one exists but it's possible there really is ONLY ONE, is this:
Code:
function getGroupValue( group )
{
if ( group == null ) { return null; } // OMIT this if you know there is at least one
if ( group.length == null ) /* handle the case of only one item in the "group" */
{
return group.checked ? [ group.value ] : null;
}
var allchecked = [ ];
for ( var g = 0; g < group.length; ++g )
{
if ( group[g].checked ) { allchecked.push( group[g].value ); }
}
return allchecked.length > 0 ? allchecked : null;
}
As I said, that will work for either checkbox groups or radio buttons. It returns an *array* of the checked values, if at least one is checked. Else it returns null.
Then you combine that with a simplified version of Andrew's suggestion to do something like:
Code:
var frm = document.getElementById('formid');
var whatIsChecked = getGroupValue( frm.pickStory ); // no need for getElementsByName
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Last edited by Old Pedant; 12-13-2012 at 12:53 AM..
Radio buttons of the same name only have one value so, just for fun!, this version will either return the value of the selected radio-button or false, with an optional error message.
Code:
function check_radios(frm, group_name, error_msg) {
// var grp = document.getElementsByName(group_name);
if (typeof(frm) === "string") {
frm = document.getElementById(frm);
}
var grp = frm[group_name];
if (grp && grp.length > 0) {
var grpLength = grp.length;
for (var i = 0; i < grpLength; i++) {
if (grp[i].checked) {
//return true;
return grp[i].value;
}
}
if (error_msg) alert(error_msg);
return false;
} else {
// couldn't get elements for some reason..
return false;
}
}
This is for radio-buttons only as, for checkboxes, it would return only the first selected value.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Last edited by AndrewGSW; 12-13-2012 at 11:01 AM..
Thanks all, yes i see now that the if test for (!rad) is senseless and not needed. You all went all out, nice work
I have to say that i poked around at different places trying to gather some knowlege to end up with what i had after some trial and error and then adding my own ideas. It could have been my search but i am pretty confident in saying that your examples are the best i found on the net, and i contribute that to this site having some of the best coders around as members.
As a *very* minor point on Andrew's code: It *IS* possible to have a single radio button. I have seen a few sites use them as a means of making people acknowledge that they have read some agreement. (A checkbox is more sensible to me, but...).
So in that case, you do need the .length == null test that I included.
Also, note that you can use my code with either radio buttons or checkboxes. Just that if you are using radio buttons you would then do
Code:
var result = getGroupValue( whatever );
if ( result != null ) { result = result[0]; }
Or you could easily create a wrapper function:
Code:
function getRadioValue( radioGroup )
{
return ( ( var result = getGroupValue( whatever ) ) == null ) ? null : result[0];
}
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Testing .length against null didn't resolve in FF as it is undefined. So I could add:
Code:
if (grp && !grp.length) {
// single element
return (grp.checked) ? grp.value : false;
}
This would return if the length were 0 ?! but it won't be..
So I would probably re-write like this:
Code:
function check_radios(frm, group_name, error_msg) {
// var grp = document.getElementsByName(group_name);
if (typeof(frm) === "string") {
frm = document.getElementById(frm);
}
var grp = frm[group_name];
if (!grp) return false; // can't reference elements
if (!grp.length) {
// single element
return (grp.checked) ? grp.value : false;
} else if (grp.length > 0) {
var grpLength = grp.length;
for (var i = 0; i < grpLength; i++) {
if (grp[i].checked) {
//return true;
return grp[i].value;
}
}
if (error_msg) alert(error_msg);
return false;
} else {
// couldn't get elements for some reason..
return false;
}
}
But, as with Old Pedant, I don't think people should use single radio buttons
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Last edited by AndrewGSW; 12-13-2012 at 09:03 PM..
Also, note that you can use my code with either radio buttons or checkboxes. Just that if you are using radio buttons you would then do
Code:
var result = getGroupValue( whatever );
if ( result != null ) { result = result[0]; }
Or you could easily create a wrapper function:
Code:
function getRadioValue( radioGroup )
{
return ( ( var result = getGroupValue( whatever ) ) == null ) ? null : result[0];
}
I think this should happen within the function. That is, if its radios, return a single value, otherwise return an array for checkboxes. But I don't mind criticism?
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Last edited by AndrewGSW; 12-13-2012 at 09:15 PM..
A silly little test, but I get an alert of true from Chrome, MSIE 9, and FireFiox.
I only did this because I have used that "test against length" code for at least 10 years now and I was sure it had worked in FF before. And it seems to.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
I *will* note that using this.form.CB.length === null will not work. Indeed, you need to let JS treat the undefined as null, for you.
But that is no different than using if ( ! CB.length ) which has to convert the undefined to a boolean value.
I, personally, prefer the == null test. Yes, it's a minor cheat. But I think that the conversion of nearly everything in the world to boolean is a bigger cheat.
After all, if ( ! CB.length ) will be true no matter if CB.length is undefined, null, a numeric zero, or even a blank string! Makes it very unclear what you are *ACTUALLY* testing for. (Okay, maybe not in the case of .length but definitely in much other code I have seen.)
ADDED: For example,
Code:
var foo = "";
... hundreds of lines of code ...
if ( foo !== "" ) { /* and explicit test for a string */ }
if ( foo != "" ) { /* almost as explicit */ }
if ( ! foo ) { /* works...but no indication we are checking for a blank string */ }
Yet I see that last construction, especially in jQuery code, all the time!
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Last edited by Old Pedant; 12-13-2012 at 09:28 PM..
Yes, your guess (assumption) was correct: I was using === . Which is why I generally prefer !something. But this can be a trap for something like length where 0 may be un-anticipated. (I anticipated this in my recent code ).
Added: I understand that in jQuery it is sometimes preferable to check .length > 0 (or just .length) with jQuery objects as testing just (element) (as opposed to !element) can fail on (some/rare) occasions.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Last edited by AndrewGSW; 12-13-2012 at 09:48 PM..
It all comes down, I suppose, to how firmly entrenched you were in strongly typed languages before you started using JavaScript.
No strongly typed language would allow if ( ! xxx ) unless xxx was of type boolean or equivalent.
Of course, no strongly typed language would understand the HTML DOM, where indeed something like formreference.fieldname can be either a single object or an array of objects. So, then, even CB.length would either be a compile-time error or it would be a number in a "real" language. <grin/>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.