Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,381
    Thanks
    264
    Thanked 32 Times in 31 Posts

    My attempt at checking radio buttons.

    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>
    Last edited by durangod; 12-13-2012 at 11:24 AM.

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    Scratch that. Looks right, to me.
    ^_^

    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".

  • #3
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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.
    Last edited by AndrewGSW; 12-12-2012 at 11:01 PM.
    "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

  • #4
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    Code:
        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
    Last edited by Old Pedant; 12-13-2012 at 12:53 AM.
    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.

  • Users who have thanked Old Pedant for this post:

    durangod (12-13-2012)

  • #6
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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.
    Last edited by AndrewGSW; 12-13-2012 at 11:01 AM.
    "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

  • Users who have thanked AndrewGSW for this post:

    durangod (12-13-2012)

  • #7
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,381
    Thanks
    264
    Thanked 32 Times in 31 Posts
    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.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    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.

  • #9
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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
    Last edited by AndrewGSW; 12-13-2012 at 09:03 PM.
    "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

  • #10
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Quote Originally Posted by Old Pedant View Post
    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?
    Last edited by AndrewGSW; 12-13-2012 at 09:15 PM.
    "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

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    Quote Originally Posted by AndrewGSW View Post
    Testing .length against null didn't resolve in FF as it is undefined.

    Hmmm..
    Code:
    <html>
    <body>
    <form>
    <input type="checkbox" name="CB" />
    <input type="button" value="check" onclick="alert( this.form.CB.length == null );" />
    </form>
    </body>
    </html>
    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.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    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!
    Last edited by Old Pedant; 12-13-2012 at 09:28 PM.
    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.

  • #13
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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.
    Last edited by AndrewGSW; 12-13-2012 at 09:48 PM.
    "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

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    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.

  • #15
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,077
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb

    Just noticed that this thread is resolved ... will post as new thread and reference this one.

    See: http://www.codingforums.com/showthre...08#post1299908


    I tried making a test HTML for 'OldPedant's post #5.
    In the process, I tried using the same type of logic to a single & multiple select box.

    It seems to work, but I would like an evaluation of the logic for the 'getSelectValue()' function.

    Is it a good way to perform the checks?
    Was/is there a way to use the original 'getGroupValue()' function with the D-Downs in one common function?
    Code:
    <!DOC HTML>
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <head>
    <title> CBox/RBtn Tests </title>
    
    </head>
    <body>
    <form id="myForm" action="" method="post" onsubmit="return false">
    <table border="1">
     <tr>
      <td valign="top"> CBox<br>
       <input type="checkbox" name="cbox" id="cb0" value="0"> 0<br>
       <input type="checkbox" name="cbox" id="cb1" value="1"> 1<br>
       <input type="checkbox" name="cbox" id="cb2" value="2"> 2<br>
       <input type="checkbox" name="cbox" id="cb3" value="3"> 3<br>
       <input type="checkbox" name="cbox" id="cb4" value="4"> 4
      </td>
      <td valign="top"> RBtn<br>
       <input type="radio" name="rbtn" value="A"> A<br>
       <input type="radio" name="rbtn" value="B"> B<br>
       <input type="radio" name="rbtn" value="C"> C<br>
       <input type="radio" name="rbtn" value="D"> D<br>
       <input type="radio" name="rbtn" value="E"> E
      </td>
      <td valign="top"> Single CBox<br>
       <input type="checkbox" name="cboxAgree" id="cbAgree" value="cbAgree"> CBox Agree
      </td>
      <td valign="top"> Single RBtn<br>
       <input type="radio" name="rbtnAgree" value="rbAgree"> RBtn Agree<br>Kinda Silly
      </td>
    
      <td valign="top">  Single DD<br>Selection<br>
       <select id="sboxS" name="sboxS">
        <option value="">Choose One</option>
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
       </select>
      </td>
      <td valign="top"> Multiple DD<br>Selection<br>
       <select id="sboxM" name="sboxM" multiple>
        <option value="">Choose One Or More</option>
        <option value="a">a</option>
        <option value="b">b</option>
        <option value="c">c</option>
        <option value="d">d</option>
        <option value="e">e</option>
       </select>
      </td>
     </tr>
    </table> <p> <button onclick="statusDisplay()">Status Report</button>
    </form>
    
    <script type="text/javascript">
    
    // Following from: http://www.codingforums.com/showthread.php?t=284053
    function getGroupValue( group ) {
        if ( group == null ) { return null; } // OMIT this if you know there is at least one 
    // handle the case of only one item in the "group"
        if ( group.length == null ) { 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; 
    }
    
    // Modified from above for Drop-Down Selections (single and multiple)
    function getSelectValue( group ) {
        if ( group == null ) { return null; } // OMIT this if you know there is at least one 
    // handle the case of only one item in the "group"
        if ( group.options.length == null ) {
          return (group.selectedIndex != -1) ? [ group.options[group.selectedIndex].value ] : null; }
    
        var allchecked = [ ];
        for ( var g = 0; g < group.options.length; ++g ) {
             if ( group.options[g].selected ) { allchecked.push( group.options[g].value ); }
        }
        return allchecked.length > 0 ? allchecked : null; 
    }
    
    function statusDisplay() {
      var frm = document.getElementById('myForm');
      var cb = getGroupValue(frm.cbox);
      var rb = getGroupValue(frm.rbtn);
      var cbA = getGroupValue(frm.cboxAgree);
      var rbA = getGroupValue(frm.rbtnAgree);
      var sbS = getSelectValue(frm.sboxS);
      var sbM = getSelectValue(frm.sboxM);
      var str = 'cbox: '+cb+'\n\nrbtn: '+rb+'\n\nsingle cbox: '+cbA+'\n\nsingle rbtn: '+rbA
              + '\n\nsingle select: '+sbS+'\n\nmultiple select: '+sbM;
      alert(str);
    }
    </script>
    
    </body>
    </html>
    Last edited by jmrker; 12-14-2012 at 06:34 PM.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •