仅在选中复选框时才应用HTML5验证

时间:2015-03-19 02:07:45

标签: html html5 validation

我有一个表单,可以让用户选择是否要接收电子邮件更新。我如何确保只需要电子邮件' (HTML5验证)如果选中接收电子邮件更新的复选框。

以下是表格:

<form>
<fieldset>
<legend><b>Details</b></legend>

<label>First Name </label><input id = "fname" type="text" autofocus="" placeholder="Enter first name" name = "fname"><br><br>
<label>Last Name </label><input type="text" placeholder="Enter last name"><br><br>
<label>Email </label><input type="email" placeholder="Enter valid email">  <button onclick="myFunction()">Help</button><br><br>

</fieldset>

<fieldset>
<legend><b>Rating</b></legend>

<label>Website Rating:</label>
 <input type="radio" name="Rating" value="1">* &#40;1 Star&#41;
 <input type="radio" name="Rating" value="2">* * &#40;2 Star&#41;
 <input type="radio" name="Rating" value="3">* * * &#40;3 Star&#41;
 <input type="radio" name="Rating" value="4">* * * * &#40;4 Star&#41;
 <input type="radio" name="Rating" value="5">* * * * * &#40;5 Star&#41;<br>

</fieldset>

<fieldset>
<legend><b>Comments</b></legend>

<label>Additional Comments:</label>
<textarea id = "feedback1" name="feedback1" rows="2" cols="60"></textarea><br>

</fieldset>

<fieldset>
<legend><b>Updates</b></legend>
Do you want to receive updates via Email?<br>
<input type="checkbox" name="updateYes" value="Yes">Yes 
<input type="checkbox" name="update" value="No" checked>No<br>
</fieldset>

<br>
<input type="reset" value="Reset">
<button onclick="myFunction2()" type = "submit">Submit</button>

</form>

<script>
function myFunction() {
    alert("Please enter a valid Email adress into the 'Email' field");
}

function myFunction2() {

    var checkedRadioButton, inputs, rating;

    inputs = document.getElementsByName("Rating");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked) {
            checkedRadioButton = inputs[i];
            break;
        }
    }   

    if (checkedRadioButton) {
        rating = ("You have rated the website " + checkedRadioButton.value + " Star") 
    } else {
        rating = ("Not Rated")
}

    alert("Thank you for your feedback " + document.getElementById('fname').value + "\n" + rating + "\n" + "Your comment was " + document.getElementById('feedback1').value);
}

</script>

0 个答案:

没有答案