2

I have a form that offers a user a choice of whether they would like to receive Email updates. How do I go about making sure that the Email is only 'required' (HTML5 Validation) if the checkbox to receive Email updates is checked.

Here is the form:

<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>
2
  • Something like this? stackoverflow.com/questions/11967519/… Commented Mar 19, 2015 at 3:10
  • Unfortunately, neither answers worked for me in that question. I would like to use only JavaScript. (I know one of the answers is in JS, but it still didn't work). Commented Mar 19, 2015 at 13:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.