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 18
  1. #1
    New Coder
    Join Date
    Nov 2012
    Posts
    14
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question Radio button validation

    Hi all,

    When it comes to JS, my knowledge is very limited so I hope I don't seem like a total noob when I ask the following.

    Basically, I have a form, with 17 options, each with 3 radio buttons. Example of 3:

    Code:
    <td><input type="radio" name="o1" value="green"></td><td><input type="radio" name="o1" value="amber"></td><td><input type="radio" name="o1" value="red"></td>
    
    <td><input type="radio" name="o2" value="green"></td><td><input type="radio" name="o2" value="amber"></td><td><input type="radio" name="o2" value="red"></td>
    
    <td><input type="radio" name="o3" value="green"></td><td><input type="radio" name="o3" value="amber"></td><td><input type="radio" name="o3" value="red"></td>
    How can I basically validate all of the radio buttons on pressing submit?

    The result I'm looking for essentially is that if at least ONE of the radio buttons is missed, then the end-user gets a pop up saying "You missed a row..." - And if possible, a pop up if all the radio buttons ARE selected which says something along the lines of "Are you sure you want to submit?" etc...

    Thank you very much in advance to anyone who can assist.

  • #2
    Senior Coder
    Join Date
    Sep 2010
    Posts
    2,451
    Thanks
    17
    Thanked 275 Times in 275 Posts
    You're using them wrong. In a group all radio buttons have the same name but different values. In that group the radio button that is chosen has its value submitted when the form is submitted.
    Welcome to http://www.myphotowizard.net

    where you can edit images, make a photo calendar, add text to images, and do much more.


    When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,316
    Thanks
    203
    Thanked 2,566 Times in 2,544 Posts
    Try this:-

    Code:
    <html>
    <head>
    
    <script type="text/javascript">
    
    var RadNames=['R1','R2','R3'];
    
    function ValidateRadios(frm) {
    var message = [];
    var selected = [];
    var answers = "";
    for (var p0 = 0; p0<RadNames.length; p0++) {
    var radobjs = frm[RadNames[p0]];
    var valid = false;
    for (var p1=0; p1<radobjs.length; p1++) {
    if (radobjs[p1].checked) {
    valid = true;
    selected[p0] = radobjs[p1].value;
    alert ("For Question " + (p0+1) + " you selected " + selected[p0]);
    // alerts are regarded as obsolete and should be used only for testing purposes.  Use DOM methods to display a message to the user.
    answers = answers += (p0+1) + ":" + selected[p0] + "\n";
    }
    }
    if (!valid) {
    message.push('Please check one from group '+(radobjs[0].title||radobjs[0].name));
    }
    }
    if (message.length>0) {
    alert (message.join('\n'));
    return false;
    }
    alert ("The responses you chose were:-   " + "\n" + answers);
    // alerts are regarded as obsolete and should be used only for testing purposes.  Use DOM methods to display a message to the user.
    return true;
    }
    
    </script>
    
    </head>
    
    <body>
    
    <form id = "myform" >
    
    Question 1 Yes <input title="Question 1" type="radio" name="R1" value = "Yes">
    No <input type="radio" name="R1" value = "No">
    Don't Know <input type="radio" name="R1" value = "Don't Know">
    <br>
    
    Question 2 Yes <input title="Question 2" type="radio" name="R2" value = "Yes">
    No <input type="radio" name="R2" value = "No">
    Don't Know <input type="radio" name="R2" value = "Don't Know">
    <br> 
    
    Question 3 Yes <input title="Question 3" type="radio" name="R3" value = "Yes">
    No <input type="radio" name="R3" value = "No">
    Don't Know <input type="radio" name="R3" value = "Don't Know">
    
    <br>
    <br>
    <input type="button" name="" value="Validate" onclick=" ValidateRadios(this.form);" >
    
    </form>
    
    
    </body>
    </html>
    As the Doctor says, all the buttons in a radio group have the same name but different values.


    Quizmaster: How many dwarves were there in the Snow White story?
    Contestant: Ten.
    Last edited by Philip M; 09-11-2013 at 04:48 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,687
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    I don't get what you guys are talking about. In what way does this code of LewisHowe *NOT* (repeat *NOT*) satisfy the condition "all the buttons in a radio group have the same name but different values"???
    Code:
    <td>
        <input type="radio" name="o1" value="green">
    </td><td>
        <input type="radio" name="o1" value="amber">
    </td><td>
        <input type="radio" name="o1" value="red">
    </td>
    And while Philip's code clearly works for the situation he shows, why not give an answer that matches the HTML he showed us??

    ***********

    I am assuming that all the radio button groups have names "o1", "o2", "o3", etc. That is, each group's name starts with the letter "o" and the groups are numbered successively from 1 to 17 (as the original post said there were 17 groups).

    SO:
    Code:
    function validateOptions( )
    {
        var form = document.forms[0]; // or document.getElementById("idOfForm")
        var oops = "";
        for ( var optnum = 1; optnum <= 3; ++optnum )
        {
            var rbgroup = form["o" + optnum];
            var okay = false;
            for ( var r = 0; r < rbgroup.length; ++r )
            {
                if ( rbgroup[r].checked ) { okay = true; break; }
            }
            if ( ! okay ) { oops += ", " + optnum; }
        }
        if ( oops != "" )
        {
            alert("You did not make any choice in row(s) " + oops.substr(2) );
            return false;
        }
        return true;
    }
    And, as Philip said, you should not be using alert( ) so treat the above as just illustrative.
    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.

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,316
    Thanks
    203
    Thanked 2,566 Times in 2,544 Posts
    Quote Originally Posted by Old Pedant View Post
    I don't get what you guys are talking about. In what way does this code of LewisHowe *NOT* (repeat *NOT*) satisfy the condition "all the buttons in a radio group have the same name but different values"???
    Ughh, I misunderstood the point of the Doctor's observation.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,687
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    Quote Originally Posted by Philip M View Post
    Ughh, I misunderstood the point of the Doctor's observation.
    LOL! Well, maybe he had his eyes crossed at 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.

  • #7
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Quote Originally Posted by Old Pedant View Post
    I am assuming that all the radio button groups have names "o1", "o2", "o3", etc. That is, each group's name starts with the letter "o" and the groups are numbered successively from 1 to 17 (as the original post said there were 17 groups).

    SO:
    Code:
    function validateOptions( )
    {
        var form = document.forms[0]; // or document.getElementById("idOfForm")
        var oops = "";
        for ( var optnum = 1; optnum <= 3; ++optnum )
        {
            var rbgroup = form["o" + optnum];
            var okay = false;
            for ( var r = 0; r < rbgroup.length; ++r )
            {
                if ( rbgroup[r].checked ) { okay = true; break; }
            }
            if ( ! okay ) { oops += ", " + optnum; }
        }
        if ( oops != "" )
        {
            alert("You did not make any choice in row(s) " + oops.substr(2) );
            return false;
        }
        return true;
    }
    optnum should be up to 17 not 3. But we can avoid having to hardcode the number of radio groups.

    Code:
    function validateOptions() {
        var oops = [],
            i = 0,
            rbgroup;
    
        while ((rbgroup = document.getElementsByName('o' + (++i))).length) {
            if (!isRadioGroupChecked(rbgroup)) {
                oops.push(i);
            }
        }
    
        if (oops.length) {
            alert('You did not make any choice in row(s): ' + oops.join(', '));
            return false;
        }
    
        return confirm('Are you sure you want to submit?');
    }
    
    function isRadioGroupChecked(rbgroup) {
        for (var j=0; j < rbgroup.length; j++) {
            if (rbgroup[j].checked) {
                return true;
            }
        }
        return false;
    }
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,687
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    I used 1 to 3 because that's all he provided in his sample. But I did mention he could go to 17 if they were numbered sequentially.

    Another way to do what Glenn is showing just means a tiny alteration to my code:
    Code:
        for ( var optnum = 1; optnum <= 999999; ++optnum )
        {
            var rbgroup = form["o" + optnum];
            if ( rbgroup == null ) break; // out of the loop
            var okay = false;
            ... rest same ...
    But it's probably all moot.

    LewisHowe hasn't bothered to respond, so this was probably a cross-post and he already got the answer someplace else. I hate crossposters.
    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
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Are you serious about suggesting to use 999999? Aside from being inefficient, why would you use an arbitrarily high number in the for-loop condition?

    You can see from this jsperf test that using while-loop is way faster than using for-loop and hardcoding 3 and 999999.

    http://jsperf.com/for-loop-cf
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,687
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    You missed the reason and import of this line completely:
    Code:
        if ( rbgroup == null ) break; // out of the loop
    BREAK! Breaks out of the for loop.

    So it stops as soon as it finds a missing element.

    It's effectively identical to your
    Code:
        while ((rbgroup = document.getElementsByName('o' + (++i))).length) {
    which also breaks out of your while loop when it reaches "o18" (or one more than whatever the max found is).

    Different syntax, same effect.
    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.

  • #11
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    I didn't miss the break statement. As you can see in the js perf test I made, using 999999 is the slowest. That's because comparing a number against 999999 is slower than comparing against 3. I know that's neglible and doesn't matter in this case. But using an arbitrary high number in a for-loop condition is not a good practice.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,687
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    I don't disbelieve you, but that's crazy. That JS implementation is badly broken.

    It should make no difference whatsoever what number you use as the loop maximum. It's still a number, and all numbers in JavaScript are (or should be!) represented in the same way "under the covers".

    If the JS is converting 999999 from the text of the code to internal number format each time through the loop, then yes, I could see that. But if that's so, then it's the most horrible compiler or pseudo-compiler implementation I've ever seen.

    Way back in 1977, when I created my first BASIC pseudo-compiler, I parsed all such string-as-numbers when the line was first encountered and then used the internal numeric representation thereafter. So FOR i = 1 TO 3 and FOR i = 1 TO 7818111.3338E+22 executed the loop at exactly the same speed.

    For any JS implementation, in 2013, to see a difference make me want to avoid it at all costs.
    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
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,687
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    Ahhh...your test is bogus!

    Because the loop with max of 3 never executes the break!

    Which means it always enters the loop only 3 times.
    Whereas any number greater than 3 causes the loop to be entered 4 times (and exited once, of course).

    I would bet that if you just changed from 3 to 4, forcing the break to be used in both cases, you'd find the timings the same.

    I do concede that the while loop is much faster; it's not clear to me why it should be so much faster. I'm guessing a poor implementation of the for statement.
    Last edited by Old Pedant; 09-13-2013 at 08:44 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.

  • #14
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    I think the document.getElementsByName() makes the while-loop much faster than the for-loop with form[elementname] syntax.

    http://jsperf.com/for-loop-cf/4
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #15
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,387
    Thanks
    32
    Thanked 288 Times in 282 Posts
    Quote Originally Posted by glenngv View Post
    I think the document.getElementsByName() makes the while-loop much faster than the for-loop with form[elementname] syntax.

    http://jsperf.com/for-loop-cf/4
    That seems to be the case. I made a new version of your test at http://jsperf.com/for-loop-cf/5 that iterates over all nine elements and compares getElementsByName with ["name"] using both loop types and getElementsByName wins hands down as far as performance goes. for yields approximately the same performance as while with while generally winning out.

    Using that test, getElementsByName is 4× faster than ["name"] in Firefox 23, 2× in Chrome 29/Opera 16, and 1.3× faster in IE11.

    IE8 in a virtual machine was the only browser I tested where ["name"] outperformed getElementsByName; performance was roughly the same for both.
    Last edited by Arbitrator; 09-14-2013 at 02:49 AM. Reason: Corrected comparative info for for versus while.
    For every complex problem, there is an answer that is clear, simple, and wrong.


  •  
    Page 1 of 2 12 LastLast

    Tags for this Thread

    Posting Permissions

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