Results 1 to 7 of 7

Thread: Elegant way of validating radio buttons with JavaScript

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Elegant way of validating radio buttons with JavaScript

    This is, for the most part, a question for you, Samba! Or someone else with plenty of JavaScripting ability.

    I'll explain my situation a little: for fun, I am making a form validating class -- no jQuery and no other libraries. Everything is fine, except I can't validate a group of radio buttons in an elegant way. My validation method works by looping through my form's elements collection (myForm.elements) and checking if fields are empty (as the most basic form of validation). however, I have four radio buttons in a group, so this loops through all four of them, which doesn't really allow me to validate them as easily as I would with other elements (without making a variable or something to hold the value, I guess?). so, originally I just checked if the element's type was a radio button and skipped it if so. then, I just added a custom validation handler manually. this works fine, but I just don't want to HAVE to have a custom validation handler for all radio buttons.

    these are the input fields on my form:
    HTML Code:
    <input type="radio" name="company" id="companyOracle" value="oracle" class="required" /> <label for="companyOracle">Oracle</label><br />
    <input type="radio" name="company" id="companyMicrosoft" value="microsoft" /> <label for="companyMicrosoft">Microsoft</label><br />
    <input type="radio" name="company" id="companySun" value="sun" /> <label for="companySun">Sun</label><br />
    <input type="radio" name="company" id="companyZend" value="zend" /> <label for="companyZend">Zend</label><br />
    so, this works great currently (function-wise):
    Code:
        validator.handler("company", function(form){
          // here, form.company is an instance of NodeList
          alert(form.company.getSelectedValue());
        });
    the getSelectedValue() method is defined on the NodeList class:
    Code:
    /**
     * Get the selected value of a node list (radio button list)
     * 
     * @return string
     */
    NodeList.prototype.getSelectedValue = function(){
      for(var i = 0; i < this.length; i++){
        if(this.item(i).checked){
          return this.item(i).value;
        }
      }
    };
    but, I'd prefer to not have to create this handler thing manually.

    when looping through my form elements, I check if the class 'required' is set on the element before doing any validation, which is why only one of these elements has required set here (otherwise, all 4 would cause validation). I can't use my NodeList method, though, because when I loop through the elements, the element reference I have is an instance of HTMLInputElement.
    Code:
    for(var i in myForm.elements){
      var e = myForm.elements[i];
      if(e.hasClass("error")){
        // e is now an HTMLInputElement
      }
    }
    so, I guess I'm curious if I would be able to get the NodeList reference from my HTMLInputElement (but the parentNode and other properties don't seem to do it) -- or if I can grab the form element like I did in my custom event handler, but dynamically using the element's name property, something like this:
    Code:
    myForm.{e.name}
    HOPEFULLY, this makes some sense. if not, I'll try explaining it better!
    Last edited by kows; Nov 6th, 2010 at 10:23 PM.
    Like Archer? Check out some Sterling Archer quotes.

  2. #2

    Thread Starter
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Elegant way of validating radio buttons with JavaScript

    also, for the record -- I know this can be solved using eval():
    Code:
    var nodeList = eval("myForm." + e.name);
    but I just don't regard it as an elegant solution, I guess.
    Like Archer? Check out some Sterling Archer quotes.

  3. #3
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Elegant way of validating radio buttons with JavaScript

    My first thought would be to use a fieldset element to wrap the radio inputs (the "required" class would then go on the fieldset rather than any of the radios). Fieldset will be part of the myForm.elements collection, then when you access its childNodes, you'll have a NodeList to work with.

    I could be entirely wrong, but my inclination is that semantically sense-making markup makes for good Javascript. Having four radio inputs with only one of them marked as "required" does not make semantic sense to me - you're required to pick one amongst that set, not that first one in particular. Hence the notion of the fieldset as the "required" element.

    But, it's Monday morning, this idea hasn't been thoroughly browser-tested, might think of something better later, my video-games-to-web-dev ratio is leaning more toward the former lately, insert additional credibility disclaimers here.

    Will post again if anything else comes to mind.

  4. #4

    Thread Starter
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Elegant way of validating radio buttons with JavaScript

    Quote Originally Posted by SambaNeko View Post
    Having four radio inputs with only one of them marked as "required" does not make semantic sense to me - you're required to pick one amongst that set, not that first one in particular. Hence the notion of the fieldset as the "required" element.
    It didn't make sense to me, either, and that's one reason I didn't like what I was doing. Still, as it stands right now, you can either have one radio button with the required class set or all of them and it will produce the same result.

    either way, I just checked to make sure (I was sure they didn't), and fieldsets do not appear in form.elements (at least not in Chrome).
    Like Archer? Check out some Sterling Archer quotes.

  5. #5
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Elegant way of validating radio buttons with JavaScript

    Quote Originally Posted by kows View Post
    either way, I just checked to make sure (I was sure they didn't), and fieldsets do not appear in form.elements (at least not in Chrome).
    Hm, yeah - as noted, not thoroughly browser-tested (it worked in Firefox... and seemingly IE8). I'll have to take another look then.

    Edit: not to be stubborn or uncreative, but I still think I'd go with a fieldset; if it isn't natively included in the form.elements collection in all browsers, then I'd probably use a "second pass" with form.getElementsByTagName to grab 'em. As said, I feel like this makes semantic sense, and isn't too complicated to implement. Though disagreement is permitted.
    Last edited by SambaNeko; Nov 8th, 2010 at 10:45 PM.

  6. #6
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Elegant way of validating radio buttons with JavaScript

    Came up with another idea, though I don't know if it qualifies as elegant... or good.

    Using your original markup for the radio inputs (not adding a fieldset), I tried...
    Code:
    HTMLFormElement.prototype.getNodeList = function(ename){
      var div = document.createElement('div');
      var elsByName = document.getElementsByName(ename);
      
      for(i=0;i<elsByName.length;i++){
        if(elsByName[i].parentNode == this){
          div.appendChild(elsByName[i].cloneNode(true));
        }
      }
      
      elsByName = div.getElementsByTagName('*');
      return elsByName;
    };
    
    for(var i in myForm.elements){
      var e = myForm.elements[i];
      if(e.type == "radio"){
        var t = myForm.getNodeList(e.name);
        alert(t.getSelectedValue());
      }
    }
    Basically using an arbitrary container element (the div) to contain clones of the radio inputs that you're interested in (matched by name, and in the context of the current form), and get a NodeList from there. I haven't tested in IE, and in Firefox, elsByName was being returned as an HTMLCollection instead of a NodeList - to accommodate this, I added the same getSelectedValue() to HTMLCollection's prototype as well.

    Making clones could have some ramifications, but if you're only interested in sniffing out the selected value in the group...

  7. #7

    Thread Starter
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Elegant way of validating radio buttons with JavaScript

    yeah, I found that when I finished IE and FireFox seem to use HTMLCollection while Chrome uses NodeList, so I put the method on the HTMLCollection's prototype as well.

    I will take a look at doing this later, as right now my solution was to do the eval() thing I mentioned.

    Thanks for the solution!
    Like Archer? Check out some Sterling Archer quotes.

Posting Permissions

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



Click Here to Expand Forum to Full Width