Javascript Radio Button Validation Error -
i can't radio button validation work correctly. check boxes , textf ield fine, radio buttons not validation checked, page not continuing on 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 fields validate go 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 page } else { errorspan.innerhtml = ""; //clear error return true; //go success page } } function validateflavor() { var flavor = document.getelementbyid("pie_form").flavor; var errorspan = document.getelementbyid("error_flavor"); errorspan.innerhtml = ""; if(!flavor.checked) { errorspan.innerhtml = "* must pick flavor."; return false; } return true; } function validatecheckbox(fieldid, errorid) { var checkbox = document.getelementbyid(fieldid); var errorspan = document.getelementbyid(errorid); errorspan.innerhtml = ""; //if didn't check checkbox show error if(!checkbox.checked) { errorspan.innerhtml = "* didn't agree have ice cream?"; return false; } //if checked return true 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"> want ice cream? </label> <span id="error_ice_cream" class="error"></span> </p> <input type="submit" name="continue" value="continue"> </form>
document.getelementbyid("pie_form").flavor
returns array. need create variable ischecked
set false, loop through array, , set variable true if 1 of radio buttons checked. continue script written.
this code works:
function validateflavor() { var flavor = document.getelementbyid("pie_form").flavor, errorspan = document.getelementbyid("error_flavor"), ischecked = false, i; errorspan.innerhtml = ""; (i = 0; < flavor.length; += 1) { if (flavor[i].checked) { ischecked = true; break; } } if (!ischecked) { errorspan.innerhtml = "* must pick flavor."; return false; } return true; }
and here's fiddle.
Comments
Post a Comment