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.
Results 1 to 14 of 14
  1. #1
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    815
    Thanks
    43
    Thanked 6 Times in 5 Posts

    jquery validating radio buttons

    Trying to validate radio buttons in jQuery.

    I've made a demo.

    http://aapress.com.au/demo/radiobutt...alidation.html

    Code:
    <!doctype html>
    <html lang="en">
    
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=utf-8" />
    <title>Jquery radio buttons validation</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <style>
    body{ font-family:arial, serif; font-size:14px}
    .error{ color:#CC0000; font-size:12px; margin:4px; font-style:italic; width:200px;}
    .success{ color:#009900; font-size:12px; margin:4px; font-style:italic; width:200px;}
    #Clear{ width: 70px;float:right;}
    #Refresh{ width: 70px;float:right;}
    #Send{ border:#CC0000 solid 1px; float:center; width: 80px; background:#C00000; color:#FFFFFF;padding:3px;}
    </style>
    </head>
    
    <body>
    
    <form action="process.php" id="myform" name="myform" method="post">
    	<div>
    		<legend>&nbsp;<label for="myoptions1"><input type="radio" id="myoptions1" value="red" name="myoptions" validate="required:true" /> 
    		red</label><label for="myoptions2">
    		<input type="radio" id="myoptions2" value="green" name="myoptions" /> 
    		green</label><label for="myoptions" class="error" style="display:none;">Please 
    		choose one option</label> </div>
    	<input value="Refresh" type="button" id="Refresh" onclick="history.go()">
    	<input value="Clear" type="reset" id="Clear"><br>
    	<input value="Send" type="submit" id="Send" name="Send"><p></p>
    </form>
    
    </body>
    
    </html>
    I realise there is something missing, but I require the error message to display if no buttons are selected. Can anyone help?
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Posts
    165
    Thanks
    1
    Thanked 39 Times in 39 Posts
    Will post a solution for you tomorrow AM. Editing HTML & JS Is nearly impossiblek from my phone

  • #3
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    815
    Thanks
    43
    Thanked 6 Times in 5 Posts
    That's very decent of you. Thanks! I've been struggling with this for days...
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #4
    Regular Coder
    Join Date
    Apr 2012
    Posts
    165
    Thanks
    1
    Thanked 39 Times in 39 Posts
    No problem what so ever! I am always willing to help. Hopefully once I'm in my office I will be able to provide you with the edits you need to make! It will probably only take me 5 to 10 minutes on my computer. But it would take me 5 to 10 hours on my stupid phone! LOL

  • #5
    Regular Coder
    Join Date
    Apr 2012
    Posts
    165
    Thanks
    1
    Thanked 39 Times in 39 Posts
    Here you go:

    HTML:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=utf-8" />
    <title>Jquery radio buttons validation</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" type="text/css" />
    <script type="text/javascript" src="validate.js"></script>
    </head>
    
    <body>
    <form action="process.php" id="cForm" method="post">
    <legend>
    <input type="radio" id="myoptions1" value="red" name="myoptions"  /> <label for="myoptions1">red</label><br />
    <input type="radio" id="myoptions2" value="green" name="myoptions" /> <label for="myoptions2">green</label><br /><br />
     
    <input value="Refresh" type="button" id="Refresh" onclick="history.go()">
    <input value="Clear" type="reset" id="Clear"><br /><br /></legend>
    <div id="errormessage"></div>
    <input value="Send" type="button" id="Send" onClick="buttonEval();"><p></p>
    </form>
    
    </body>
    </html>
    New CSS stylesheet named "style.css"
    Code:
    body{ 
    font-family:arial, serif; 
    font-size:14px
    }
    
    #errormessage {
    color:#CC0000; 
    }
    .error{ 
    color:#CC0000; 
    font-size:12px; margin:4px; 
    font-style:italic; 
    width:200px;
    }
    
    .success{ 
    color:#009900; 
    font-size:12px; 
    margin:4px; 
    font-style:italic; 
    width:200px;
    }
    
    #Clear{ 
    width: 70px;float:right;
    }
    
    #Refresh{ 
    width: 70px;float:right;
    }
    
    #Send{ 
    border:#CC0000 solid 1px; float:center; 
    width: 80px; 
    background:#C00000; 
    color:#FFFFFF;
    padding:3px;
    }
    new JS file named "validate.js"
    Code:
     function buttonEval () {
                var cForm = document.getElementById("cForm");
                           
                 if (document.getElementById("myoptions1").checked || document.getElementById("myoptions2").checked) {
                        selected = true;
                  }
    
                else {
                    document.getElementById("errormessage").innerHTML="Please choose one option.<br /><br />";
                    return;
                }
    
                cForm.submit ();
            }

  • Users who have thanked EpicWebDesign for this post:

    tpeck (06-09-2012)

  • #6
    Regular Coder
    Join Date
    Apr 2012
    Posts
    165
    Thanks
    1
    Thanked 39 Times in 39 Posts
    Quote Originally Posted by iBall View Post
    <offTopic style="tip">



    Imo that is a very inefficient way of validating radio buttons because if you ever need to add or remove radio buttons from the set, then you will also have to edit the javascript.

    If you use getElementsByName() to get the set of radio buttons and loop through them checking the checked property, then you can add or remove radio buttons in the future as much as you like without having to edit the javascript at all


    <offTopic>
    Agree with you, but simply addressed the OP's code as provided. I'm always willing to provide alternate solutions if they require more extensive functionality, and have done so whenever requested.

  • #7
    Regular Coder
    Join Date
    Apr 2012
    Posts
    165
    Thanks
    1
    Thanked 39 Times in 39 Posts
    Again, I agree you with you. I don't feel that my role here is to anticipate every scenario that the OP will need. I answer direct questions posed (based on code provided ) and address them per the OP question. If that offends you in any way, I apologize. I offer my suggestions and code as direct answers to the question /code provided. I have never suggested that my code is in any way better than the options provided by other members of this forum. I simply try to provide a working example to the OP. I have no desire to get in a "pissing contest" with you or any other member.

    I feel I have been respectful to your responses and would appreciate the same. My only goal here is to offer potential solutions to the original question/code posted. I don't, nor will ever, claim to provide the ultimate solution to any question asked here. I just offer potential solutions and am willing to expand when requested.

    I hope this clarifies my intent.
    Last edited by EpicWebDesign; 06-09-2012 at 02:49 AM. Reason: typos due to posting from phone LOL

  • #8
    Regular Coder
    Join Date
    Apr 2012
    Posts
    165
    Thanks
    1
    Thanked 39 Times in 39 Posts
    <completely offTopic!>
    Quote Originally Posted by iBall View Post
    Again, no problem and I am not offended at all.

    All I did was point out why imo, (as I stated), your suggestion was less efficient than it could be. It was more for the op's benefit, not yours

    But you keep harping on about answering the questions posed and although your suggestion is one possible solution, it doesn't address the op's question at all because the op said

    and I don't see any jquery in your code.

    Even the title of the thread is
    My apologies for the 2nd? 3rd? time.... you win this round *congrats* However, your solution (while more flexible than mine) did not utilize jquery either.

    I work 16+ hrs per day for paying clients and then TRY to offer my help here for FREE when I can. I am not perfect, nor have I ever claimed to be. I do not consider myself the guru of the ever-changing world of web design/coding (which I have been involved in since 1990). That is nearly impossible due to the continual changes made to the various coding languages and browsers!

    Yes...there are days that I may not be as "on top of my game" as I should be. However, unless you are perfect in every aspect of your life, I would hope that you could relate to that and be a little less abrasive in your comments.

    In that regard, I don't consider 2 responses (ever) to you as "harping" on a topic. If you are that invested in my involvement here, please feel free to go through every post/suggestion I've ever made. I'll be more than happy to give you credit for correcting any misunderstanding of an OP's question and/or my oversight in what their intentions were.

    This is not FaceBook. I'm in my 40's, not my teens. In my opinion, this forum shouldn't be drama/ego based. If you have an improvement or correction on any piece of code I've provided, then thank you!!! -- Please post it and then move on. If I've over-looked something vital, made a coding error, or simply wasn't forward-thinking enough, then please feel free to point it out (as you obviously have). I have no problem with that. I just don't see the need to take such an offensive/personal-attack approach instead of simply posting something like, "Hey, I can improve on that last suggestion with...."

    I've read many of your posts and you do have some great suggestions, however, your signature is quite off-putting (to me personally). It implies a need to always win every battle, even when there is not a competition in place. If you choose to ignore everyone who may not always agree with your opinion, you simply cloak yourself in false sense of reality.

    I wish you the best, but will politely decline from further discussion of this very off-topic subject. If you feel the need to respond again, you are welcome to PM me.</offTopic>
    Last edited by EpicWebDesign; 06-09-2012 at 04:27 AM.

  • Users who have thanked EpicWebDesign for this post:

    Philip M (06-10-2012)

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,590
    Thanks
    0
    Thanked 644 Times in 634 Posts
    Quote Originally Posted by iBall View Post
    and I don't see any jquery in your code.
    There isn't anything in jQuery that would assist in validating radio buttons. The most you could do with jQuery and radio button validation is to have both present in the same page.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    815
    Thanks
    43
    Thanked 6 Times in 5 Posts
    Well, I'm happy with all the answers, guys. I was going nowhere. I still haven't got the getElementsByName() working in jQuery but it's my lack of jQuery knowledge.
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #11
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,590
    Thanks
    0
    Thanked 644 Times in 634 Posts
    Quote Originally Posted by tpeck View Post
    Well, I'm happy with all the answers, guys. I was going nowhere. I still haven't got the getElementsByName() working in jQuery but it's my lack of jQuery knowledge.
    getElementsByName() isn't part of jQuery - it is ordinary JavaScript. There isn't any JavaScript in jQuery to help with validating radio buttons - to do it with jQuery results in adding code to jQuery that is at least as long as the code needed without jQuery.

    validating radio buttons using ordinary JavaScript takes very little code. With a radio button group with name="myoptions" all the code you need is:

    Code:
    var valid = false;
    var buttons = document.getElementsByName('myoptions');
    for (var i = buttons.length - 1; i >= 0; i--) {
       if (buttons[i].checked) valid = true;
    }
    Once you've run that you can then simply use if (valid) to control what you want to do next.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    tpeck (06-09-2012)

  • #12
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,882
    Thanks
    56
    Thanked 539 Times in 536 Posts
    it would seem to me that you can just count how many elements of that name are checked and if it's more than none, submit the form...
    Code:
    <script type="text/javascript">
    $("form").submit(function() {
    	if($("[name='myoptions']:checked", this).length > 0){ 
    	return true; 
    	} else{
    	document.getElementById("errormessage").innerHTML="Please choose one option.<br /><br />";
        return false;
    	}
    });
    </script>

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,590
    Thanks
    0
    Thanked 644 Times in 634 Posts
    Quote Originally Posted by iBall View Post
    Then I would do what I suggested in post 5

    Code:
            
           <script type="text/javascript">
                function isRadButtonChecked(radBtnName){
                    var isBtnChecked = false;
                    var radBtnsO = document.getElementsByName(radBtnName);
                    for(i=0; i<radBtnsO.length; i++){
                        if(radBtnsO[i].checked){
                            isBtnChecked = true;
                            i = radBtnsO.length;  //exit loop, no need to check rest of buttons
                        }
                    }
                    return isBtnChecked;
                }
            </script>
    The only other thing that you can do to improve on that is to reverse the order in which you process the loop so that you don't need to calculate adBtnsO.length each and every time around the loop. Not that you'd notice the small amount of extra time that extra calculation takes but the code is no harder to write and understand if you start from length - 1 and go to 0 instead of the other way around.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #14
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,590
    Thanks
    0
    Thanked 644 Times in 634 Posts
    Quote Originally Posted by iBall View Post
    yep, that's true. But in terms of readability and slightly less code I prefer to count up, as it seems most people do.

    I suppose you could, as another option, also just do

    Code:
    var len = myArray.length;
    
    for(i=0; i < len; i++).................
    Agreed. Some people even combine that into one line as:

    Code:
    for (i = 0, len = myArray.length; i < len; i++)
    I think that about covers all the alternatives. These two are slightly less efficient than the count down because they have one extra statement to run while the original variant is slightly less efficient than these because it has to implicitly run that extra statement each time around the loop - not that the differences are big enough to measure unless you run the code millions of times.

    They'd all be identical if JavaScript were a compiled language as the compiler would work out the most efficient variant.

    Which of the four variants you use in this particular situation doesn't really matter since the same result is obtained whichever way around the loop you go - it simply demonstrates that there are several ways to do even simple things in JavaScript. There are situations where processing in reverse order can result in much simpler code though (such as looping over elements in the web page deleting some of them as you go) so it is worthwhile keeping the alternatives in mind.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

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