Required fields but ONLY if data entered in another field that isn't required
I have a form that allows users to enter textbook information for their course. They need to include information such as author, publisher, book title, isbn, etc. They can enter information for more than one book if they choose.
I need to write some code that makes the publisher and book title fields required...but ONLY if they choose to add a first, second, third book.
I guess what I'm looking for is some help on how to create required fields that are dependent on some other field being selected/checked.
Here is a longer explanation for you
How do you do a "required field" in JavaScript? The answer is that you have an onSubmit method on the form that returns false if validation fails. It might also do an alert. So expanding the example you gave:
Code:
<script>
function checkForm() {
if ( document.getElementById("1_1").checked ) {
var mytext = document.getElementById("1a").value;
if ("" == mytext) {
alert("Explanation needed for No answer to question #1");
return false;
}
}
return true;
}
</script>
<form onSubmit="return checkForm()">
<p>1. *Question goes here*</p>
<p>
<label>
<input type="radio" name="1" value="Yes" id="1_0" />Yes</label>
<br />
<label>
<input type="radio" name="1" value="No" id="1_1" />No</label>
<label></label>
<br />
</p>
<p> </p>
<p>1a. If not, why not?</p>
<p> </p>
<p>
<textarea name="1a" id="1a" cols="60" rows="5"></textarea>
</p>
<input type=submit></input>
</form>
Now be warned that anyone who wants can bypass JavaScript checks by just turning JavaScript off. Or by copying your page, manually editing out the JavaScript, and then submitting from that. Therefore if it really matters to you, all validation checks must happen on the server side, and the JavaScript checks are just a convenience for your users. Getting that set up is beyond what I'm willing to answer in this post.