首页 > 解决方案 > 在 jquery 和验证检查中动态添加复选框

问题描述

我有一个小问题。我有一个由一排复选框组成的主要类别。在这个主要类别中,我有一个按钮 Add Section,它在上面的行下添加另一行复选框,并在每次单击 Add Section 后继续添加另一行复选框。

在框外,我有一个主按钮,允许添加另一个主类别。原理是一样的,都是加了一行复选框,后面跟着一个section按钮。如果我想在这个类别中再次添加另一行,我只需单击Add Section按钮。

问题是我遇到了,我无法在单击时添加另一行Add section按钮时添加另一行。另外,我想从第二行的复选框中验证 as,这样如果我选中第二行中的第一个复选框,我应该能够选中第三行中的第一个复选框。

主类别中的第一行复选框独立于第二行复选框和以后的行(即添加部分时创建的行

我已经完成了验证,如下所示: https ://jsfiddle.net/fL3hekhw/

已编辑

演示是: https ://jsfiddle.net/fL3hekhw/

当我单击框中的“添加部分”按钮时,它不应复制其他框中添加的复选框。我怎样才能防止这种情况?请帮忙。

有人可以帮我吗?我完全被困住了。

标签: javascriptjqueryhtml

解决方案


您链接到的演示存在一些问题。

  1. 你要求,.closest('.js-cars-items')但你只用作.js-cars-item一个类
  2. 当您添加新复选框时,您正在重新使用 id,这在整个文档中必须是唯一的
  3. 添加新类别时,您没有使用添加的新.cars元素注册“更改”事件侦听器

我做了一些小的重构,希望能让代码更容易阅读。我还完全删除了麻烦的调用,因为无论如何.closest('.js-cars-items')你已经在迭代了。.js-cars-item

不过,我只是不确定一件事。您是否希望在所有类别或每个类别中验证列中的复选框?

let nextSection = 4;
const carsItemSelector = '.js-cars-item [type="checkbox"]';

function registerValidation() {
  $(".main").on("change", carsItemSelector, validateCategorySelection);
}

function validateCategorySelection() {
  const idx = $(this).closest('li').index(); //Get the index - Number in order
  const chk = $(this).is(":checked"); //Get if checked or not
  const obj = this; //Checkbox object

  $('.js-cars-item').each(function() { //Loop every js-cars-item
    //Find the checkbox with the same index of clicked checkbox. Change disabled property
    $(this).find('li:eq(' + idx + ')')
           .find('[type="checkbox"]')
           .not(obj)
           .prop("checked", false);
  });

  var checkeds = [];
  $(".cars-item input:checkbox:checked").each(function(index) {
    checkeds[index] = $(this).attr('id');
  });
  console.clear();
  console.log("These are checked:", checkeds);
}

function checkbox(index, section) {
  return `
    <li>
      <input type="checkbox" id="car-${index}-${section}">
      <label for="car-${index}-${section}"><i class="icon-tick"></i></label>
    </li>
  `;
}

registerValidation();
$('.js-add-category').click(function() {
  const section = nextSection;
  nextSection++;
  var categoryContent =
    `<div class="cars">
    <div class="cars-item js-cars-item">
      <ul>
        ${[1, 2, 3].map(i => checkbox(i, section)).join('\n')}
      </ul>
    </div>

    <button type="button" class="js-add-section">Add Section</button>
  </div>
  <br>`

  $('.main').append(categoryContent);
  // registerValidation();
});

$(document.body).on('click', 'button.js-add-section', function() {
  const section = nextSection;
  nextSection++;
  var sectionContent =
    `<div class="cars-item js-cars-item">
    <ul>
        ${[1, 2, 3].map(i => checkbox(i, section)).join('\n')}
    </ul>
  </div>`
  $(this).closest('.cars').append(sectionContent);
});
.cars-item {
  border-bottom: 1px solid gray;
}

ul {
  /* Added to fully show console in snippet */
  margin: 2px;
}

li {
  display: inline;
}

.cars {
  box-sizing: content-box;
  width: 250px;
  height: auto;
  padding: 10px;
  border: 5px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="js-add-category">Add Category</button> <br> <br>

<div class="main">

  <div class="cars">

    <div class="cars-item js-cars-item">
      <ul>
        <li>
          <input type="checkbox" id="car-1-3">
          <label for="car-1-3"><i class="icon-tick"></i></label>
        </li>
        <li>
          <input type="checkbox" id="car-2-3">
          <label for="car-2-3"><i class="icon-tick"></i></label>
        </li>
        <li>
          <input type="checkbox" id="car-3-3">
          <label for="car-3-3"><i class="icon-tick"></i></label>
        </li>
      </ul>
    </div>



    <button type="button" class="js-add-section">Add Section</button>
  </div>
  <br>



  <br>


推荐阅读