根据用户输入设置选中的复选框

2023-12-31

我有这些 HTML 元素:

<div>
    <form>
        <div class="form-group">
            <label class="control-label"></label>
            <input type="text" value="1100" class="myCars">
        </div>
    </form>
    <form>
        <div class="form-group">
            <label class="control-label"></label>
            <input type="text" value="0011" class="myCars">
        </div>
    </form>
</div>

这是我的复选框:

var elem = $('.myCars');
var car = ['car1', 'car2', "car3", "car4"];
var container = '<ul class="cars">';

for (i = 0; i < car.length; i++) {
    container += '<li>' +
        '<label class="container ' + car[i] + '">' +
        '<input type="checkbox">' +
        '<span class="checkmark"></span>' +
        '</label>' +
        '</li>';

}
container += '</ul>'
elem.closest('div').append(container);

配置复选框后,我想遍历所有输入并将复选框设置为选中,其中输入值为 1

我已经尝试过这个:

$('.myCars').each(function() {
    var arr = $(this).val()
    var array = arr.split('')
    // array values: 
    Array(4)["1", "1", "0", "0"]
    Array(4)["0", "0", "1", "1"]

    $('.myCars').prop('checked', function(index) {
        return +array[index] === 1;
    });
})

我怎样才能让它发挥作用?


您的问题的一个可能的答案是:

// select the .myCars elements, and bind the anonymous function
// of the on() method as the event-handler for the 'input'
// event:
$('.myCars').on('input', function() {

  // retrieve the entered value, and then use String.prototype.trim()
  // to remove leading/trailing white-space:
  let enteredValue = $(this).val().trim(),

    // convert that String into an Array, using
    // String.prototype.split('') (as in your own posted code), then
    // use Array.prototype.map() to iterate over every Array value
    // with a call to the Number() function to convert the entered
    // values to Numbers:
    valueArray = enteredValue.split('').map(Number);

  // navigate to the closest ancestor <div> element:
  $(this).closest('div')
    // find the <input type="checkbox"> elements:
    .find('input[type=checkbox]')
    // update the 'checked' property using the anonymous function,
    // here we pass in the index of the current element:
    .prop('checked', function(index) {
      // we return the assessment of whether the array-value at
      // the current index is exactly equal to 1 (if true this
      // checks the check-box, if false it unchecks the box, or
      // leaves it unchecked); this is why we used the call to
      // Array.prototype.map(Number) earlier:
      return valueArray[index] === 1;
  });

// triggering the 'input' event so the checkboxes are updated
// on page load:
}).trigger('input');
var elem = $('.myCars');

var car = ['car1', 'car2', "car3", "car4"];
var container = '<ul class="cars">';

for (i = 0; i < car.length; i++) {
  container += '<li>' +
    '<label class="container ' + car[i] + '">' +
    '<input type="checkbox">' +
    '<span class="checkmark"></span>' +
    '</label>' +
    '</li>';

}
container += '</ul>'
elem.closest('div').append(container);

$('.myCars').on('input', function() {
  let enteredValue = $(this).val().trim(),
    valueArray = enteredValue.split('').map(Number);
  $(this).closest('div').find('input[type=checkbox]').prop('checked', function(index) {
    return valueArray[index] === 1;
  });
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <form>
    <div class="form-group">
      <label class="control-label"></label>
      <input type="text" value="1010" class="myCars">
    </div>
  </form>
  <form>
    <div class="form-group">
      <label class="control-label"></label>
      <input type="text" value="0011" class="myCars">
    </div>
  </form>
</div>

JS 小提琴演示 https://jsfiddle.net/davidThomas/rz5e2Lvs/.

上面的替代方案如下,仅使用普通的 DOM API。请注意,在这种方法中我使用了<template>元素,而不是创建一个 HTML 字符串并包装整个<form>中的元素one <form>:

// using let, rather than var, as personal preference in this
// case; using document.querySelectorAll() to retrieve a
// non-live NodeList of the elements matching the supplied
// CSS selector:
let elems = document.querySelectorAll('.myCars'),
  car = ['car1', 'car2', "car3", "car4"],

  // using `document.createElement()` to create the <ul>:
  container = document.createElement('ul');

// retrieving the content of the <template> element, accessed
// via its id (using a CSS selector), and the content property:
template = document.querySelector('#carCheckboxes').content,

  // creating an InputEvent:
  inputEvent = new Event('input'),

  // defining the function to handle updates to the checkboxes,
  // passing in the Event Object (here referred to as 'e'):
  updateCheckmarks = (e) => {

    // e.currentTarget is the element to which the event-listener
    // is bound:
    let source = e.currentTarget,

      // here we retrieve the value of the current element,
      // use String.prototype.trim() to remove the leading/
      // trailing white-space, use String.prototype.split('')
      // to convert the String to an Array of characters, and
      // and finally a call to Array.prototype.map(Number)
      // (as above) to convert the array-entries into numbers:
      value = source.value.trim().split('').map(Number),

      // here we find the check-boxes, navigating to the
      // closest ancestor <div>:
      checkmarks = source.closest('div')
        // and finding the <input type="checkbox"> elements within:
        .querySelectorAll('input[type=checkbox]');

    // using Array.prototype.forEach() to iterate over that Array;
    // check: the (user defined name for) the current <input> element,
    // index: the (user defined name for) the index of the current
    // <input> in the Array over which we're iterating:
    checkmarks.forEach(function(check, index) {

      // here we set the checked property to true/false,
      // depending on the following assessment:
      check.checked = value[index] === 1;
    });
  };

// iterating over the car Array, using Array.prototype.forEach():
car.forEach(function(el) {

  // cloning the content template, including descendant elements
  // using Node.cloneNode(true):
  let model = template.cloneNode(true);

  // appending that cloned node to the container:
  container.appendChild(model);
})

// iterating over the elems Array:
elems.forEach(
  // using an Arrow function; 'el' is the (user defined name
  // for) the current element of the Array of elements:
  (el) => {

    // appending a cloned container Node to the closest
    // ancestor <div> element:
    el.closest('div').appendChild(container.cloneNode(true));

    // binding the updateCheckmarks() function as the
    // event-handler for the 'input' event:
    el.addEventListener('input', updateCheckmarks);

    // firing the inputEvent (created earlier) on the
    // the current element, in order to trigger the
    // function on page-load:
    el.dispatchEvent(inputEvent);
  });
let elems = document.querySelectorAll('.myCars'),
  car = ['car1', 'car2', "car3", "car4"],
  container = document.createElement('ul');
template = document.querySelector('#carCheckboxes').content,
  inputEvent = new Event('input'),
  updateCheckmarks = (e) => {
    let source = e.currentTarget,
      value = source.value.trim().split('').map(Number),
      checkmarks = source.closest('div').querySelectorAll('input[type=checkbox]');
    checkmarks.forEach(function(check, index) {
      check.checked = value[index] === 1;
    });
  };

car.forEach(function(el) {
  let model = template.cloneNode(true);
  container.appendChild(model);
})

elems.forEach(
  (el) => {
    el.closest('div').appendChild(container.cloneNode(true));
    el.addEventListener('input', updateCheckmarks);
    el.dispatchEvent(inputEvent);
  });
<template id="carCheckboxes">
  <li>
  <label>
    <input type="checkbox"><span class="checkmark"></span>
  </label>
  </li>
</template>
<div>
  <form>
    <div class="form-group">
      <label class="control-label"></label>
      <input type="text" value="1010" class="myCars">
    </div>
    <div class="form-group">
      <label class="control-label"></label>
      <input type="text" value="0011" class="myCars">
    </div>
  </form>
</div>

关于你的问题,评论里 https://stackoverflow.com/questions/53115315/set-checkboxes-checked-based-on-user-input/53115730#comment93127434_53115771,到另一个答案:

[我]可以[如何]使用onClick更改每个复选框的值? [因为]当[I]这样做时,所有输入中的复选框的值都会发生变化。

这可以使用:

// while this code - in my example - runs after the <input>
// elements are created, and appended to the DOM, we're
// binding the event-handler, using the on() method, to
// already-existing elements; so here we select the <form>
// element, and bind the anonymous function of the on()
// method as the 'change' event-handler:
$('form').on('change', function(e) {

  // caching variables:
  let form = $(this),
      valuesInput = form.find('.myCars'),

      // finding the <input type="checkbox"> elements within
      // the <form> element:
      checkboxValues = form.find('input[type=checkbox]')

        // using map() - the jQuery method - to iterate over
        // the collection to form an Array-like Object:
        .map(function(index, el) {

          // here we return 1 (if the current element is checked),
          // or 0 if it is not checked:
          return el.checked ? 1 : 0;
    // using the get() method to convert the Array-like Object
    // into an Array:
    }).get()
    // using join() to convert that array into a String, passing
    // in an empty string ('') to act as the joining characters
    // (if no argument is passed the default is a comma):
    .join('');

  // updating the value of the <input class="myCars"> element:
  valuesInput.val(checkboxValues);

// firing the 'change' event on page-load so that the value of
// the text-input reflects the checked/unchecked state of the
// checkboxes:
}).trigger('change');
let elem = $('.myCars'),
    car = ['car1', 'car2', "car3", "car4"],
   container = '<ul class="cars">';

for (i = 0; i < car.length; i++) {
  container += '<li>' +
    '<label class="container ' + car[i] + '">' +
    '<input type="checkbox">' +
    '<span class="checkmark"></span>' +
    '</label>' +
    '</li>';

}
container += '</ul>'
elem.closest('div').append(container);

$('.myCars').on('input', function() {
  let enteredValue = $(this).val().trim(),
      valueArray = enteredValue.split('').map(Number);
  $(this).closest('div').find('input[type=checkbox]').prop('checked', function(index) {
    return valueArray[index] === 1;
  });
}).trigger('input');

$('form').on('change', function(e) {
  let form = $(this),
      valuesInput = form.find('.myCars'),
      checkboxValues = form.find('input[type=checkbox]').map(function(index, el) {
        return el.checked ? 1 : 0;
    }).get().join();
    
  valuesInput.val(checkboxValues);
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <form>
    <div class="form-group">
      <label class="control-label"></label>
      <input type="text" value="" class="myCars">
    </div>
  </form>
  <form>
    <div class="form-group">
      <label class="control-label"></label>
      <input type="text" value="0011" class="myCars">
    </div>
  </form>
</div>

参考:

  • CSS:
    • 属性选择器 https://www.w3.org/TR/2018/PR-selectors-3-20180911/#attribute-selectors.
  • JavaScript:
    • Array.prototype.forEach() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach.
    • Array.prototype.join() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join.
    • Array.prototype.map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map.
    • HTMLTemplateElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement.
    • HTMLTemplateElement.content https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content.
    • Node.cloneNode() https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode.
    • Number() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number.
    • String.prototype.split() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split.
    • String.prototype.trim() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim.
  • HTML:
    • <template> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template.
  • jQuery:
    • closest() http://api.jquery.com/closest/.
    • find() http://api.jquery.com/find/.
    • get() http://api.jquery.com/get/.
    • map() http://api.jquery.com/map/.
    • on() http://api.jquery.com/on/.
    • prop() http://api.jquery.com/prop/.
    • trigger() http://api.jquery.com/trigger/.
    • val() http://api.jquery.com/map/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据用户输入设置选中的复选框 的相关文章

  • 在 HTML 中移动选取框/下移文本

    我正在尝试向下移动或移动 HTML 中的文本 但我似乎无法将其移动到任何地方 我添加了一个颜色命令来更改文本的颜色 但似乎只是移动了 它一直到顶部
  • 引入 V8 后,Google Apps 脚本无法为其他用户完全执行

    我编写了一个脚本 得到了这里好心人的大力帮助 该脚本使用 Google Sheets 脚本复制 Google Drive 上的文件夹 和内容 它运行了很长一段时间 但后来我启用了 V8 引擎 现在已禁用 问题是 它仍然适用于我 也许还有其他
  • CSS:将加载指示器放置在屏幕中央

    如何将加载指示器放置在屏幕中央 目前我正在使用一个小占位符 它似乎工作得很好 但是 当我向下滚动时 加载指示器保持在该预定义位置 我怎样才能让它跟随滚动 使其始终位于顶部 busy position absolute left 50 top
  • 只需编辑 .css 即可更改

    有 4 div class myField 每一个都在另一个之下 http jsfiddle net urielz 6Mdmd http jsfiddle net urielz 6Mdmd 我想将其视图更改为两对情侣面对面 就像结果一样 h
  • JQuery DataTable 单元格从行单击

    我正在尝试在 jquery 数据表上实现一个函数 该函数返回单击行的第一列和第四列 我正在遵循这个示例 它允许我操作单击的行http datatables net examples api select single row html ht
  • Chrome Javascript 调试器暂停时不会重新加载页面

    有时 当我在 Chrome 中调试某些 javascript 并且暂停了 javascript 时 如果我尝试重新加载页面 chrome 只会 继续 调试器 单步执行到下一个断点 似乎没有任何方法可以强制 javascript 完全停止运行
  • 使用 JavaScript 的计时器

    我想使用java脚本实现计时器 我想随着间隔的变化而减少计时器 Example假设我的计时器从 500 开始 我想要根据级别减少计时器 例如1 一级定时器应减1 且递减速度应较慢 2 2级定时器应递减2 递减速度应为中等3 3级定时器应减3
  • 元素中优先考虑 ngclick 而非 nghref

    tl dr 如何强制 Angular 只执行 ngclick 指令 a 元素而不清空 删除href 我的网站在某些元素上有一些自定义行为 模式打开 位置栏更新等 但对于 SEO 索引我also需要它成为一个 a 元素与href包含有效链接的
  • 如何在 angularjs 中修剪()字符串?

    有角度特定的方法吗 如果没有 我应该使用内置的jquery 来做到这一点吗 如果我应该使用内置的jquery 如何在不使用 的情况下访问trim 函数 或者这是必要的 编辑 是的 我知道 str trim 对不起 我需要这个才能在 IE 8
  • 理论上防止 WebSocket 中第一个收到的消息丢失

    服务器端代码发送消息立即地连接打开后 它向客户端发送初始配置 问候语 以下代码是在客户端 var sock new WebSocket url sock addEventListener error processError sock ad
  • Meteor.js 登录事件

    因此 我对 Meteor 框架和 JavaScript 总体来说还很陌生 但我正在使用该框架开发一个小项目 以尝试让自己达到标准 基本上我正在开发一个微博客网站 目前 用户可以通过多种服务登录 fb google 等 我通过插入所需 url
  • 为什么我需要 $(document.body) 来使用 Mootools Element 方法扩展 document.body?

    因此 在尝试让我的应用程序在最新的 IE 上运行后 结果发现 IE 不喜欢以下代码 document body getElement className Firefox 和 Chrome 响应良好 但是document bodyIE 上没有
  • 使用文本遮盖视频

    是否可以使用 HTML CSS 文本来屏蔽视频 我已经找到并设置了这种工作方式 但没有一种允许文本后面有透明背景 例如 这支笔要求您进行某种填充 它并不是真正掩盖实际视频 而是创造幻觉 https codepen io dudleystor
  • 常规 JavaScript 可以与 jQuery 混合使用吗?

    例如 我可以采用这个脚本 来自 Mozilla 教程 https developer mozilla org en Canvas tutorial Basic usage
  • 使用 jQuery 修改 HTML 表格的结构

    我有一个元素列表 X在以下示例中 显示在 HTML 表格的行或列中 从 HTML 代码的角度来看 我有 水平显示 table tr td A td td B td td C td tr table 或 垂直显示 table tr td A
  • 在 Google Apps 脚本中的文本前插入换行符

    我需要在 Google 文档中的某些文本之前插入一些换行符 尝试过这种方法但出现错误 var body DocumentApp getActiveDocument getBody var pattern WORD 1 var found b
  • 如何清除隐藏上的引导模式

    如何在关闭 隐藏 关闭时清除引导模式 我有以下模态定义
  • 如何根据所需表单输入的值更改 CSS 样式

    我想知道如何编写 javascript 来改变所需的表单元素的样式 如果它们有价值的话就改变它们 我想要做的是当所需的文本字段为空时 在它们周围有一个彩色边框 并在它们有值时删除边框样式 我想做的是编写一个 javascript 函数来检查
  • 未捕获(承诺中)TypeError:无法读取 null popover.js 的属性“模板”

    当我触发时我注意到一个错误 popover dispose 当我上下滚动页面时 函数会发生错误 并且它会减慢我的页面速度 该函数按其应有的方式运行并关闭弹出窗口 但这就是错误Uncaught in promise TypeError Can
  • 获取淘汰赛中被点击元素的索引

    获取无序列表中单击元素的索引的最佳方法是什么 让我举个例子 假设我有以下 HTML 代码 ul li p p li ul 现在我有以下 javascript 代码来获取索引 self itemClicked function data it

随机推荐

  • 如何在 Android 平板电脑 Chrome 中隐藏工具栏以获得 100% 高网站

    我正在尝试制作一个 100 屏幕宽度和 100 屏幕高度 长宽比为 16 9 的 Web 应用程序 如果我能够在平板电脑上全屏查看该网站 那就太棒了 但不幸的是 屏幕上的工具栏占用了大量空间 使我的网站既不能以全高也不能以全宽显示 现在我知
  • 在项目中使用 ShareKit 时,本地化字符串并不总是有效

    因为我从我的应用程序中删除了一些本地化 所以我遇到了这个问题 第一次加载我的应用程序时 我在标签中看到我的密钥的本地化字符串 第二次加载应用程序时 出现 xxxxxkey 下次加载应用程序时 一切都很好 显示本地化字符串 怎么会这样 如果有
  • 如何在 Swift 包管理器中添加本地库作为依赖项

    如何在 Swift 包管理器中添加本地库 a 文件 作为依赖项 我尝试在我的 Package swift 中添加 dependencies Dependencies declare other packages that this pack
  • Google SignIn 在应用程序中,无需将其添加到设备帐户中

    我们一直通过 WebView 使用 Google 登录 但由于 Google 很快就会弃用此功能 是否有其他替代方法可以做到这一点 我们有一个稍微特殊的用例 我们的设备在仓库中使用 并且一台设备由多个用户使用 我们不希望所有用户将他们的帐户
  • UIBarButtonSystemItem PageCurl 不随工具栏改变颜色

    我想改变导航栏和工具栏的颜色 但是卷页系统图标的颜色UIBarButtonSystemItemPageCurl不随工具栏色调颜色改变 如果我使用书签等其他系统图标 它们会改变 有人有解决此类问题的方法吗 我使用以下几行来更改导航栏和工具栏的
  • 如果访问X86系统中不存在的物理地址怎么办?

    我正在开发一个 Linux 内核模块 它通过处理进程的页表将物理地址范围映射到进程虚拟地址空间 然后 我脑子里有一个问题 如果PTE指向一个不存在的物理地址会发生什么 例如 我的 X86 笔记本电脑有 8GB DRAM 如果 PTE 的值为
  • Flexbox div 不占据整个宽度

    我试图理解如何display flex有效 但每当我设置它时 孩子们都不会占据整个宽度 我预计三个 div 会占据屏幕宽度的 33 我究竟做错了什么 flexbox display flex flexbox div border 1px s
  • 创建一个 DateTimeOffset,设置为与服务器不同时区的午夜

    我有一个设置为 EST 的服务器 我想知道我需要做什么来创建设置为当天午夜但在不同时区的 DateTimeOffset 例如太平洋标准时间 获取相关的TimeZoneInfo 构造一个DateTime其中包含local时间 即午夜 Call
  • C++(11):如果两者都很好,何时使用直接初始化或复制初始化

    在重复的呼喊开始之前 我知道以下问题 以及其他一些问题 与此问题非常相关 在 C 中 复制初始化和直接初始化之间有区别吗 https stackoverflow com questions 1051379 is there a differ
  • 使用 android 捕获按键

    如何使用 android SDK 捕获手机按键 我已经环顾了几个小时没有找到任何东西 例如 在某些情况下 我想在用户按下手机上的 挂断 按钮时捕获消息 然后在消息到达操作系统之前将其丢弃 这可能吗 您可以处理视图中的关键事件 也可以处理整个
  • C 中 read() 和 fgets() 之间的区别

    我想从标准输入流中读取数据 使用 read 或 fgets 从 stdin 流读取有什么区别吗 我用 fgets 附加了以下两段代码并阅读 有了fgets 我可以使用java程序轻松地编写和读取c程序 通过读写 我的 java 程序挂起 等
  • 如何一次将多个值分配给一个结构体?

    我可以在 Foo 结构体的初始化中执行此操作 Foo foo bunch of things initialized 但是 我不能这样做 Foo foo foo bunch of things initialized 那么 两个问题 为什么
  • 如何使用 React.js 在 Botframework v4 聊天应用程序中执行发送“打字指示器”?

    我正在使用 botframework v4 构建一个聊天应用程序 以 React js 作为前端 以 net core 作为后端来生成令牌 我想使用 React 在我的聊天中实现 Typing 指示器 尝试使用 window WebChat
  • Ubuntu 上的 rpy2 安装

    我对 Linux 还很陌生 在安装 Rpy2 时遇到了一些严重的问题 我通过突触包管理器安装了旧版本的 Rpy2 但我需要更新版本并将其删除 如 Rpy2 文档中所述 Rpy2 目录中的所有文件 我下载了tar gz 来自 SourceFo
  • 如何使用 Timer 创建时钟?

    我正在尝试创建一个七段显示 它使用计时器以及 ActionListener 和 actionPerformed 自动移动 我认为如果我使用 for if 语句 它会自动从 0 循环到 2 并为每个数字段设置背景颜色 但是 当我显示它时 它停
  • HtmlAgility:没有出现任何内容(C#,UWP)

    我尝试使用 htmlagilitypack 来解析表格 完成后我意识到我忘记证明 htmlagility 部分是否有效 很明显它不起作用 我也不知道我错过了什么 我在哪里做错了 因为我是初学者 所以请不要对我太严厉 public parti
  • 获取资源错误

    每次我在主要活动中调用 getResources 时 都会导致错误并且应用程序被迫退出 如果我调用 getApplicationContext getResources 甚至在 Eclips 中的全新项目中也会发生这种情况 在通话之前我需要
  • 使用 CSS 替换 ul 项目符号点样式

    我想替换 ul 列表的列表样式类型属性 以便外部是一个圆盘 然后一个内部 ul 列表是一个圆 再一个内部是一个圆盘 依此类推 本质上 我想要的是这样的 ul li Lorem ipsum li li ul li Lorem ipsum li
  • 如何将匿名类型转换为已知类型

    我有一个匿名类型变量 该变量是从另一个函数获取的 我们无法更改它 var a property1 abc property2 def 我有一堂课 class Myclass string property1 string property2
  • 根据用户输入设置选中的复选框

    我有这些 HTML 元素 div div