Sage K
Sage K

Reputation: 13

Javascript Radio Button Validation Error

I can't get the radio button validation to work correctly. The check boxes and textf ield are fine, but the radio buttons are not validation as checked, so the page is not continuing on to the success page.

<script>
        window.onload =function()
        {
            document.getElementById("pie_form").onsubmit = validateForm;
        }

        function validateForm()
        {
            var validName = validateTextBox("pie_name", "error_pie_name");
            var validFlavor = validateFlavor("flavor", "error_flavor");
            var validIceCream = validateCheckBox("ice_cream", "error_ice_cream");

            //if all fields validate go to next page
            return validName && validFlavor && validIceCream;
        }

        function validateTextBox(fieldId, errorId)
        {
            var text = document.getElementById(fieldId).value;
            var errorSpan = document.getElementById(errorId);

            if(text == "")
            {
                errorSpan.innerHTML = "* blank";
                return false;   //stay on this page
            }
            else
            {
                errorSpan.innerHTML = "";   //clear the error
                return true;    //go to success page
            }
        }


        function validateFlavor()
        {
            var flavor = document.getElementById("pie_form").flavor;
            var errorSpan = document.getElementById("error_flavor");
            errorSpan.innerHTML = "";

            if(!flavor.checked)
            {
                errorSpan.innerHTML = "* You must pick a flavor.";
                return false;
            }

            return true;
        }

        function validateCheckBox(fieldId, errorId)
        {
            var checkbox = document.getElementById(fieldId);
            var errorSpan = document.getElementById(errorId);
            errorSpan.innerHTML = "";

            //if you didn't check the checkbox show error
            if(!checkbox.checked)
            {
                errorSpan.innerHTML = "* You didn't agree to have Ice Cream?";
                return false;
            }

            //if you checked return true to say its valid
            return true;
        }

    </script>
</head>
<body>
    <h1>Pie Festival!</h1>

    <form id="pie_form" action="pie_success.html">
        <p>
            <label>Pie Name:
                <input type="text" id="pie_name" name="pie_name">
            </label>
            <span id="error_pie_name" class="error"></span>
        </p>            
        <p>
            Flavor:
            <span id="error_flavor" class="error"></span><br>
            <label><input type="radio" name="flavor" value="apple">Apple</label><br>
            <label><input type="radio" name="flavor" value="blueberry">Blueberry</label><br>
            <label><input type="radio" name="flavor" value="cherry">Cherry</label><br>
        </p>
        <p>
            <label>
                <input type="checkbox" id="ice_cream" name="ice_cream">
                Do you want Ice Cream?
            </label>
            <span id="error_ice_cream" class="error"></span>
        </p>

        <input type="submit" name="continue" value="Continue">
    </form>

Upvotes: 0

Views: 2734

Answers (4)

RobG
RobG

Reputation: 147343

It is a good idea to always have one radio button checked by default, however sometimes that doesn't suit. You can reference the form controls as properties of the form, so form.flavor will return an HTMLCollection of the controls with a name of flavour. You can then loop over them to see if one is checked, e.g.

function validate(formId) {
  var form = document.getElementById(formId);
  var radios = form.flavor;
  var oneChecked = false;

  for (var i=0, iLen=radios.length; i<iLen && !oneChecked; i++) {
    oneChecked = radios[i].checked
  }

  return oneChecked;
}

Upvotes: 0

Amazing Sey
Amazing Sey

Reputation: 69

You didn't give any IDs to the radio elements so you can't use getelementbyid and also radio group gives a list so you must loop through thus revised validateflavor function below works:

function validateFlavor(fieldName, errorId) {
    var errorSpan = document.getElementById(errorId);
    errorSpan.innerHTML = "";
    var flavorgroups = document.getElementsByName(fieldName)

            for (var i = 0; i < flavorgroups.length; i++) {
                if (flavorgroups[i].checked) {
                return true; // checked
            }
            };

            // not checked, show error
            errorSpan.innerHTML = '* You must pick a flavor.';
            return false;
        }

Upvotes: 0

Derek Henderson
Derek Henderson

Reputation: 9706

document.getElementById("pie_form").flavor returns an array. You need to create a variable like isChecked set to false, loop through the array, and set your variable to true if one of the radio buttons is checked. Then continue with your script as written.

This code works:

function validateFlavor() {
    var flavor = document.getElementById("pie_form").flavor,
        errorSpan = document.getElementById("error_flavor"),
        isChecked = false,
        i;

    errorSpan.innerHTML = "";

    for (i = 0; i < flavor.length; i += 1) {
        if (flavor[i].checked) {
            isChecked = true;
            break;
        }
    }

    if (!isChecked) {
        errorSpan.innerHTML = "* You must pick a flavor.";
        return false;
    }

    return true;
}

And here's a fiddle.

Upvotes: 1

Carlo Moretti
Carlo Moretti

Reputation: 2250

I suggest you to try use some jQuery and use the :checked selector like this:

$('form').submit(function(e){

    e.preventDefault()

    if($('input[name=flavor]:checked').size() < 1){

        ... do ya thing...

    }else{

        $(this).submit()

    }

you should really use jQuery as it is clean an pretty and easier to debug.

HERE THE WORKING FIDDLE

Edit

The selector :checked is basically a CSS selector thus can be used to select the checked element by jQuery selector. You can learn more about :checked selector here

Upvotes: 0

Related Questions