在if语句中添加if语句

时间:2011-11-30 13:47:47

标签: javascript jquery forms validation

我有一个提交表单的按钮功能。此功能检查是否选中了5个复选框#co1,#co2,#co3,#div1,#cc1。

然后还检查tcaccept select是否设置为1。 如果是,则提交表单,否则弹出警报。

这是我目前的代码:

  $('#submit2pd').click(function(event) {
    var $finishBoxes = $('#co1,#co2,#co3,#div1,#cc1');

        if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' )) {
    alert('Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College');
            return false;
        }

        // otherwise the form is submitted
        window.location.href = "submit2pd.php";

    });

一切都很出色,但我想添加到这一行,因为我有另一个选项是必需的。但这必须是一个if语句。

    if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' && THE IF STATEMENT))

这是我需要纳入上面的if语句。

if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank
}

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

怎么样:

if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && 
    $('#tcaccept').val() == '1' && 
    !($("#ctl").val() == "1" && $('#ctlapp').val() === "")))

我们在此处添加的是另一个条件,即"并确保#ctl不是1,#ctlapp为空白&# 34。

编辑:请参阅上面的评论 - 您的问题不是关于jQuery,表单或验证。它几乎与JS无关。

答案 1 :(得分:1)

if($('#tcaccept').val() == '1' && validate()) {
 // do something
}

var validate = function(){
  if ($("#ctl").val() == "1") {
    $('#ctlapp') must not be blank
    return false;
  }
  else if ($("#ctl").val() == "0") {
    $('#ctlapp') can be blank;
    return true;
  }
  return true;
}

答案 2 :(得分:1)

我会说清理一下代码,事情会变得更简单:

$('#submit2pd').click(function(event) {
    var fail_message = 'Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College',
        $finishBoxes = $('#co1,#co2,#co3,#div1,#cc1'),
        $checkedBoxes = $finishBoxes.filter(':checked'),
        tcaccept = $('#tcaccept').val(),
        ctl = $("#ctl").val(),
        ctlapp = $('#ctlapp').val();

    if (tcaccept == '1' && $finishBoxes.length != $checkedBoxes.length ) {
        alert( fail_message );
        return false;
    } else if( ctl == "1" && ctlapp == "" ) {
        alert( "some other message" );
        return false;
    }

    // otherwise the form is submitted
    window.location.href = "submit2pd.php";
});

我离开了$('#ctl').val() == "0"的测试,因为听起来这是它可以拥有的唯一其他值,并且如果它是"0"则无需进行验证。

答案 3 :(得分:0)

使用逻辑或||捕获两个常量:

$(“#ctl”)。val()==“1”&& $('#ctlapp')!=“”

OR

$(“#ctl”)。val()==“0”

if (
  !(
    $finishBoxes.length == $finishBoxes.filter(':checked').length 
  && 
    $('#tcaccept').val() == '1' 
  && 
    ( 
       ($("#ctl").val() == "1" && $('#ctlapp') != "")
    ||
       $("#ctl").val() == "0"
    )
  )
)