【问题标题】:jQuery multiple conditional statementsjQuery 多条件语句
【发布时间】:2021-07-15 17:32:32
【问题描述】:

我有这个代码:

    $('#inputID').on('keyup', function () {
      if ($('#inputID').val() == '') {
          $(".button").removeClass('uk-button-success');
      } else {
          $(".button").addClass('uk-button-success');
      }
    })

它需要填充单个输入,因此特定按钮会添加一个类。 现在我想检查多个输入,如果所有输入都已填充且不为空,我想将“uk-button-success”类添加到按钮。

 if ($('#inputID', '#inputID2').val() == '')

我尝试过的其他方法都不起作用。

我该怎么做?

【问题讨论】:

  • 您可以尝试使用逻辑OR 运算符:if ($('#inputID').val() == '' || $('#inputID2').val() == '' || ...) { /* some of them is empty */} else {/* all are filled */}
  • 这行得通,很好!我现在如何使用 keyup 功能获取多个 ID? $('#inputID1', '#inputID2').on('keyup', function () { 不起作用。
  • @IhorVyspiansky 有更好的方法,见下文;)
  • @Jonas 例如,为所有输入设置相同的类名。让它成为my-input。然后你可以使用$('.my-input').on('keyup', function () {...?
  • @StéphaneM 据我了解,它只允许检查单击的输入值($(this).val()),但不能检查其他输入(引用:I want multiple inputs to be checked and if all of them are filled and not empty)。

标签: jquery forms input


【解决方案1】:

只需按类定位以具有多个元素,然后使用 $(this)

例如:在一批输入中禁用(或不)提交以下所有值。

$(function() {
  $('.input').on('keyup', function() {
    result = true
    $('.input').each(function() {
      if ($(this).val() === '') {
        result = false
      }
    })
    result ? $("#target").prop('disabled', false) : $("#target").prop('disabled', true);
  });
});

https://jsfiddle.net/g84p5b6v/

您的基本用例

$(function() {
    $('.input').on('click', function () {
      if ($(this).val() === '') {
          $("#target").removeClass('success');
      } else {
          $("#target").addClass('success');
      }
    })
});

=> https://jsfiddle.net/45of2nrk/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多