Reputation: 87
I have another logic question that I am getting stuck with. I need this form to only allow either one or the other. Either the text input or the checkbox, not both!
}else if(question_pos==7){
if(!($('#test_check').prop('checked')) && $("#test").val()!="0" && ($("#test").val() =="" ||
!Number($("#test").val()) || Number($("#test").val())<0 || Number($("#test").val())>20 )){
alert("placeholder?");
return false;
the inputs:
<table class="screening" width="100%" cellspacing="5px">
<tr>
<td width="8%" align="right"><input name="test" id="test" type="text" pattern="\d*" size="3" maxlength="2" value="<%=session.getAttribute("test")==null?"":session.getAttribute("test")%>"/>
</td>
<td>day(s)</td>
</tr>
<tr>
<td width="8%" align="right" valign="top"><input name="test_check" id="test_check" type="checkbox" value="1" <%=(session.getAttribute("test_check")!=null && session.getAttribute("test_check").equals("1"))?"checked":""%>/></td>
<td width="92%"><label for="test_check">My baby is still in the hospital</label></td>
</tr>
</table>
The validation needs to make sure that there is no text input if the checkbox is checked.
Upvotes: 0
Views: 285
Reputation: 87
This is what ended up working exactly how I needed it. I just had to drink some coffee and wake up!
}else if(question_pos==7){
if(!$('#example_check').prop('checked') && $("#example").val()!="0" && ($("#example").val() =="" || !Number($("#example").val()) || Number($("#example").val())<0 || Number($("#example").val())>20 )){
alert("How long did your baby stay in the hospital?");
return false;
}else if($('#example_check').prop('checked') && $("#example").val().length) {
alert("Have you taken your baby home or is your baby still in the hospital?");
return false;
I changed the "test" to "example"
Upvotes: 0
Reputation: 43728
Basically, you want to check if the checked
property is true and if the field contains some characters. If both conditions are met, it means the form's state is invalid.
Here's an example http://jsfiddle.net/g4q34/
You should avoid calling $("#test")
over and over, it makes the code less readable and is very inefficient performance-wise. Store a reference in a variable and reuse that variable instead.
var checked = $('#test_check').prop('checked'),
val = $("#test").val();
if (checked && val.length) {
//invalid
} else {
//the checkbox is checked OR the input contains text, but not BOTH
}
Here's an example with your own code:
} else if (question_pos==7) {
if($('#test_check').prop('checked') && $("#test").val().length) {
alert("placeholder?");
return false;
}
Upvotes: 1