0

我还有另一个我遇到的逻辑问题。我需要这个表格来只允许一个或另一个。文本输入或复选框,而不是两者!

}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;

输入:

    <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>

如果选中复选框,则验证需要确保没有文本输入。

4

2 回答 2

1

基本上,您想检查该checked属性是否为真以及该字段是否包含某些字符。如果两个条件都满足,则表示表单的状态无效。

这是一个示例http://jsfiddle.net/g4q34/

您应该避免$("#test")一遍又一遍地调用,它会降低代码的可读性并且在性能方面非常低效。将引用存储在变量中并重用该变量。

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
}

这是您自己的代码的示例:

} else if (question_pos==7) {
        if($('#test_check').prop('checked') && $("#test").val().length) {
            alert("placeholder?");
            return false;
        }
于 2013-04-17T23:11:06.587 回答
0

这就是我最终需要的工作方式。我只需要喝点咖啡就醒了!

}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;

我将“测试”更改为“示例”

于 2013-04-18T15:56:54.930 回答