hey guys i just try to do some validate for my javascript radio button, but is not work. every time i click submit button it just nothing happened.below is the code.
HTML part
<form name="FirstPizza">
<td>
Style:
<br/>
<input type="radio" name="style"/>
Thin Crust
<br />
<input type="radio" name="style" />
Deep Dish
<br />
<input type="radio" name="style" />
Sicilian
</td>
</form>
Javascript:
function submitForm(){
if((!form.style[0].checked) && (!form.style[1].checked) && (!form.style[2].checked))
{
window.alert("You must have a style")
}
i should come with a box but nothing happen. Do i miss something?
You were close! According to your comment, your form
variable was not defined. You need to define form
somewhere like this:
function submitForm() {
// define the form variable
var form = document.getElementsByName("FirstPizza")[0];
if((!form.style[0].checked) && (!form.style[1].checked) && (!form.style[2].checked)) {
window.alert("You must have a style");
} else {
window.alert("a style was selected");
}
}
(see working jsfiddle here )
Use IDs for your form controls! Try this:
HTML part
<form name="FirstPizza">
<td>
Style:
<br/>
<input type="radio" id="rbThinCrust" name="style"/>
Thin Crust
<br />
<input type="radio" id="rbDeepDish" name="style" />
Deep Dish
<br />
<input type="radio" id="rbSicilian" name="style" />
Sicilian
</td>
</form>
Javascript:
function submitForm(){
if (!document.getElementById("rbThinCrust").checked && !document.getElementById("rbThinCrust").checked && !document.getElementById("rbThinCrust").checked)
//Logic for nothing being checked
}
Both your HTML and JavaScript are completely broken.
First, your HTML. You have no HTML for a button there, which you need should you wire your javascript event to it in the first place.
You would create a submit button like this:
<input type="submit" value="Submit" onclick="submitForm(this)" />
Your radio buttons also should have their text set via the value
attribute, like so:
<input type="radio" name="style" value="Thin Crust" />
<input type="radio" name="style" value="Deep Dish" />
<input type="radio" name="style" value="Sicilian" />
Now your javascript, it should look something more like this:
function submitForm(form){
if((!form.style[0].checked) && (!form.style[1].checked) && (!form.style[2].checked))
{
window.alert("You must have a style")
}
Hope that works for you.
And your end HTML should look like this:
<form name="FirstPizza">
Style:<br />
<input type="radio" name="style" value="Thin Crust" />Thin Crust<br />
<input type="radio" name="style" value="Deep Dish" />Deep Dish<br />
<input type="radio" name="style" value="Sicilian" />Sicilian
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.