首页 > 解决方案 > jquery如何获取未在布尔值中选择的复选框输入?

问题描述

在 jquery 3.4.1 应用程序中,我定义了复选框

<div class="form-row mb-3 mt-3">
    <label for="step_2_invoice_on_next_period_cbx" class="col-12 col-sm-6 col-form-label">Invoice on next period</label>
    <div class="col-12 col-sm-6">
        <input type="checkbox" value="1" style="width: 50px;padding-left: 10px; margin-top: 7px;"
               id="step_2_invoice_on_next_period_cbx"
               checked>
    </div>
</div>

如果选择了复选框输入,我得到了有效的真值。但是如果未选择复选框输入,我会得到未定义,我需要设置附加条件:

var step_2_invoice_on_next_period_cbx= $("#step_2_invoice_on_next_period_cbx:checked").val()
if(typeof step_2_invoice_on_next_period_cbx=='undefined') step_2_invoice_on_next_period_cbx= false

看起来它工作正常,但如果有更好的方法来获得有效的真/假条件而无需附加检查线?

谢谢!

标签: javascriptjquery

解决方案


解决方案

这是您应该这样做的方式,这种方式将在checkbox检查时侦听(或truefalse它是如何做到这一点的该事件正在检查属性是否为或( ) 如果在我的代码示例中这是真的,我们将使用of to when和when更改元素的文本。checkboxstepTwoInvoiceOnNextPeriodCbx.click()stepTwoInvoiceOnNextPeriodCbx.click()checkedtruefalsestepTwoInvoiceOnNextPeriodCbx.prop("checked")id#text"Is checked"true"is not checked"false

JavaScript

let stepTwoInvoiceOnNextPeriodCbx = $(
  "#step_2_invoice_on_next_period_cbx"
);
let text = $("#text"); // This is just here to show output of the example

// Listen for checkbox to be click
stepTwoInvoiceOnNextPeriodCbx.click(() => {
  // If the checked property
  if (stepTwoInvoiceOnNextPeriodCbx.prop("checked")) {
    // Is true set text to "Is checked"
    text.text("Is checked");
  } else {
    // Is false set text to "Is not checked"
    text.text("Is not checked");
  }
});

HTML

<div id="app">
  <div class="form-row mb-3 mt-3">
    <label
      for="step_2_invoice_on_next_period_cbx"
      class="col-12 col-sm-6 col-form-label"
      >Invoice on next period</label
    >
    <div class="col-12 col-sm-6">
      <input
        type="checkbox"
        value="1"
        style="width: 50px; padding-left: 10px; margin-top: 7px;"
        id="step_2_invoice_on_next_period_cbx"
        checked
      />
    </div>
    <span id="text"></span>
  </div>
</div>

这是我制作的一个示例,您可以看到它是如何工作的https://codesandbox.io/s/compassionate-blackwell-d9hex?file=/src/index.js

你的代码在做什么

您正在检查value属性的数据类型是否是"undefined","undefined"undefined是两个不同的东西,因为您正在检查数据的类型,您告诉计算机要做的是检查value属性的类型是否等于 ( ==) a string(文本数据类型)值为undefined( "undefined") 此比较不检查您必须使用相同运算符 ( ===) 的数据类型 此检查值和数据类型是否相同。在您的情况下,获取 L 元素的属性的方法val()将始终是因为它从未设置过。valueHTMundefined

您对此进行编码的方式也意味着它只会在页面加载后运行,因为您没有监听事件(如click()在我的示例中),该click()事件意味着只要#step_2_invoice_on_next_period_cbx单击该元素就运行事件内部的函数click()

其他要记住的事情

PHP在 JavaScript 中,使用 camelcase 命名变量和函数是一种很好的做法,而不是像使用蛇形大小写 ( ) 这样的下甲类 (snakecase) 语言,this_is_snake_case而在 JavaScript 中我们使用骆驼大写 (),thisIsCamelCase但我们倾向于使用 pascalcase ( ThisIsPascalCase) 来命名类名。


推荐阅读