Search code examples
javascriptjquerycssradio-buttonrating

Pure CSS Star Rating - Enforce Non-Zero Result


I've been using the pure CSS example found here: http://www.danielkeithjones.com/Articles/Web_Development/Pure_CSS_5_Star_Rating_System_with_Radios/

But I cannot figure out how to prevent the form from submitting when there are zero stars selected (which it initiates as). Basically: if the star-based question is required I want to say "it has to be 1-5 stars" but since the default is 0 JavaScript seems to ALWAYS think it's zero until the form saves.

What am I missing?

Here is the JavaScript I'm using:

    // Check radio buttons
    jQuery("input.input-required:radio").each(function() {
        var name = jQuery(this).attr("name");
        var group = jQuery("input:radio[name='"+name+"']");
        radio_groups[name] = false;
        radio_groups[name] = (radio_groups[name] == true) || (group.is(":checked") && group.val() != "0 stars");
    });
    for(var key in radio_groups) {
        if(radio_groups.hasOwnProperty(key) && radio_groups[key] == false) {
            alert("This question is required");
            return false;
        }
    }

Solution

  • I'm not sure what your HTML looks but with the following html:

    <form>
      <input type="radio" name="testing" value="0 stars" class="input-required" checked>
      <input type="radio" name="testing" value="1 stars" class="input-required">
      <input type="radio" name="testing" value="2 stars" class="input-required">
      <input type="radio" name="testing" value="3 stars" class="input-required">
      <input type="radio" name="testing" value="4 stars" class="input-required">
      <input type="radio" name="testing" value="5 stars" class="input-required">
      <button type="submit">Submit</button>
    </form>
    

    and the following js:

    $('form').on('submit', function(){
        var valid=true;
        $('input.input-required:radio').each(function(){
            if (valid) {
              var name = this.name,
                  value = $('input[name="' + name + '"]:checked').val();
              if (value == "0 stars"){
                alert('This question is required');
                valid=false;
              }
            }
        });
        return valid;
    });
    

    It works.