如何使用多条件if-function工作的功能?

时间:2018-05-18 15:28:19

标签: javascript jquery

我有一个由一些元素组成的表单,例如select-input和checkbox。

提交按钮已禁用,我只想在满足两个条件时启用该按钮。初始版本运行良好,但只有单击复选框才是最后一步。但它应该是对select和复选框中的点击/更改做出反应的函数。

以下代码正在运行,但上述问题已解决。

$('#toscheck').click(function() {
    if ($(this).is(':checked') && $("#ctry").val().length > 0) {
      $('#pjo').removeAttr('disabled');
      $('#sjo').removeAttr('disabled');
    } else {
      $('#pjo').attr('disabled', 'disabled');
      $('#sjo').attr('disabled', 'disabled');
    }
});

以下解决方案无效:

$('document').ready(function() {
    if ($('#toscheck').is(':checked') && $("#ctry").val().length > 0) {
      $('#pjo').removeAttr('disabled');
      $('#sjo').removeAttr('disabled');
    } else {
      $('#pjo').attr('disabled', 'disabled');
      $('#sjo').attr('disabled', 'disabled');
    }
});

但我怎么能解决这个问题?我在SO上找到的并不是很有帮助。

再次:它应该如下工作;如果选中该复选框并且所选选项具有值,则该按钮将被启用。

提前致谢。

2 个答案:

答案 0 :(得分:2)

首先,将元素存储在变量中:

let $toscheck = $('#toscheck'),
    $ctry = $("#ctry"),
    $pjo = $('#pjo'),
    $sjo = $('#sjo');

然后,使用存储的变量创建验证函数。请注意,我将attrremoveAttr替换为.prop,它更好:

function checkThings(){
    if ($toscheck.is(':checked') && $ctry.val().length > 0) {
        $pjo.prop('disabled', false);
        $sjo.prop('disabled', false);
    } else {
        $pjo.prop('disabled', true);
        $sjo.prop('disabled', true);
    }
}

然后,绑定事件:

$toscheck.add($ctry).on( 'change', checkThings );

请注意,我在两个元素上都使用了change,因为它可以使用输入和复选框。

最终代码:

let $toscheck = $('#toscheck'),
    $ctry = $("#ctry"),
    $pjo = $('#pjo'),
    $sjo = $('#sjo');

function checkThings(){
    if ($toscheck.is(':checked') && $ctry.val().length > 0) {
        $pjo.prop('disabled', false);
        $sjo.prop('disabled', false);
    } else {
        $pjo.prop('disabled', true);
        $sjo.prop('disabled', true);
    }
}

$toscheck.add($ctry).on( 'change', checkThings );

答案 1 :(得分:1)

$(document).ready(function() {
$('#toscheck,#ctry').change(function() {
    if ($('#toscheck').is(':checked') && $("#ctry").val().length > 0) {
  $('#pjo').removeAttr('disabled');
  $('#sjo').removeAttr('disabled');
} else {
  $('#pjo').attr('disabled', 'disabled');
  $('#sjo').attr('disabled', 'disabled');
}
});

});

使用此代码 .change函数检测到变化,然后通话,检查你的AND条件是否满足

并在引号中添加#toscheck,即'#toscheck'

$('#toscheck,#xyz,#abc').change()

用于检测多个元素的变化