我无法让单选按钮验证正常工作。复选框和文本字段都很好,但是单选按钮没有被选中,所以页面没有继续到成功页面。
<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>