javascript - 验证 jquery 中动态生成的复选框

标签 javascript jquery

我有以下代码笔。它的作用是,我们可以添加Add Category,它将生成一个蓝色框,最初在cars-item js-cars-item类中嵌入一行复选框。然后我们有不同的部分,用户可以在单击添加部分时添加几行复选框。这将嵌入到 js-cars-item-sub-items

类中

我能够在 js-cars-item-sub-items 类中的复选框上实现验证。也就是说,如果我选中第 2 节中第一行中的第一个复选框,当我单击第 3 节中第二行中的第一个复选框时,它会取消选中第 2 节中的复选框,并选中第 3 节中的复选框。此验证仅发生在部分(绿色框)。

现在,我想要实现的是主行复选框(红色框)中的相同行为 - 也就是说,如果我添加另一个类别,然后选中第一个类别中的第一个复选框,当我选中相同的复选框时第二个类别中的复选框,它应该取消选中第一个类别中的复选框。

谁能帮我解决这个问题?我完全被困住了。

var categoryCount = 1;

$('.js-add-category').click(function() {
	categoryCount++;
  var categoryContent = `<br><div class="serv-content">
     <div class="title-content">
     <input type="text" id="name-title-`+categoryCount+`" class="name-title" value="category-`+categoryCount+`">
     </div>
       

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

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

  $('.main-content').append(categoryContent);

});

var count = 1;

$(document.body).on('click', 'button.js-add-section', function() {

//count++;
let count = $(this).parent().parent().find('.cars-item').length+1;


  var sectionContent = `<div class="cars-item js-cars-item-sub-items">
      <ul>
        <li>
          <input type="checkbox" id="car-1-2">
          <label for="car-1-2"><i class="icon-tick"></i></label>
        </li>
        <li>
          <input type="checkbox" id="car-2-2">
          <label for="car-2-2"><i class="icon-tick"></i></label>
        </li>
        <li>
          <input type="checkbox" id="car-3-2">
          <label for="car-3-2"><i class="icon-tick"></i></label>
        </li>
      </ul>      
      <div class="footer">
          <span class="num"> Section`+count+` </span>
      </div>
</div>`

$(this).closest('.serv-content').append(sectionContent);

});

$(document.body).on('click', 'button.js-save-section', function() {
		// get selected checkboxes's values
});


// validate checkboxes for sub items..

     $(".main-content").on('change', '.js-cars-item-sub-items [type="checkbox"]', function () {
        var idx = $(this).closest('li').index(); //Get the index - Number in order
        var chk = $(this).is(":checked"); //Get if checked or not
        var obj = this; //Checkbox object

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

        var checkeds = [];
        $(this).closest(".serv-content").find(".js-cars-item-sub-items input:checkbox:checked").each(function (index) {
            checkeds[index] = $(this).attr('id');
        });
        console.clear();
        console.log("These are checked:", checkeds);
    });
    
// validate checkboxes for main items.. 

$(".main-content").on('change', '.js-cars-item [type="checkbox"]', function () {
        var idx = $(this).closest('li').index(); //Get the index - Number in order
        var chk = $(this).is(":checked"); //Get if checked or not
        var obj = this; //Checkbox object

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

        var checkeds = [];
        $(this).closest(".serv-content").find(".js-cars-item input:checkbox:checked").each(function (index) {
            checkeds[index] = $(this).attr('id');
        });
        console.clear();
        console.log("These are checked:", checkeds);
    });
.js-cars-item {
  box-sizing: content-box;
  width: auto;
  height: auto;
  padding: 10px;
  border: 3px solid red;
}

.js-cars-item-sub-items {
  box-sizing: content-box;
  width: auto;
  height: auto;
  padding: 10px;
  border: 3px solid green;
}


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

li {
  display: inline;
}

.serv-content {
  box-sizing: content-box;
  width: 250px;
  height: auto;
  padding: 10px;
  border: 5px solid blue;
}

.cars.saved {
  border-color: green;
}
<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-content">
  <div class="serv-content">
     <div class="title-content">
     <input type="text" id="name-title-1" class="name-title" value="category-1">
     </div>
       

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

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

  </div>
  <br> <br>

最佳答案

当您使用语法 $(this).closest('.serv-content').find('.js-cars-item').each() 循环遍历复选框时,问题就出现了 您只循环调用者复选框的父 .serv-content 类,因为对象 this 代表调用者复选框而不是其他 .serv-content 复选框。

因此,为了循环访问其他 .serv-content,我向所有 .serv-content div 添加了一个 id您正在创建,当您单击复选框时,我将循环遍历所有具有类 .serv-content 但不具有 iddiv调用者的。

首先,我对 $('.js-add-category').click()

上的代码进行了更改

from this:

var categoryContent = `<br><div class="serv-content">

to this:

var categoryContent = `<br><div id="serv-` + categoryCount + `" class="serv-content">

然后对复选框的点击函数进行了更改 $(".main-content").on('change', '.js-cars-item [type="checkbox"]', function() { });

From this:

$(".main-content").on('change', '.js-cars-item [type="checkbox"]', function () {
    var idx = $(this).closest('li').index(); //Get the index - Number in order
    var chk = $(this).is(":checked"); //Get if checked or not
    var obj = this; //Checkbox object

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

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

To This:

$(".main-content").on('change', '.js-cars-item [type="checkbox"]', 
function() {
 var idx = $(this).closest('li').index(); //Get the index - Number in order
 var chk = $(this).is(":checked"); //Get if checked or not
 var obj = this; //Checkbox object
 var callerId = $(this).closest('.serv-content').attr('id');

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

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

这是完整的代码片段。

var categoryCount = 1;

$('.js-add-category').click(function() {
  categoryCount++;
  var categoryContent = `<br><div id="serv-` + categoryCount + `" class="serv-content">
     <div class="title-content">
     <input type="text" id="name-title-` + categoryCount + `" class="name-title" value="category-` + categoryCount + `">
     </div>
       

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

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

  $('.main-content').append(categoryContent);

});

var count = 1;

$(document.body).on('click', 'button.js-add-section', function() {

  //count++;
  let count = $(this).parent().parent().find('.cars-item').length + 1;


  var sectionContent = `<div class="cars-item js-cars-item-sub-items">
      <ul>
        <li>
          <input type="checkbox" id="car-1-2">
          <label for="car-1-2"><i class="icon-tick"></i></label>
        </li>
        <li>
          <input type="checkbox" id="car-2-2">
          <label for="car-2-2"><i class="icon-tick"></i></label>
        </li>
        <li>
          <input type="checkbox" id="car-3-2">
          <label for="car-3-2"><i class="icon-tick"></i></label>
        </li>
      </ul>      
      <div class="footer">
          <span class="num"> Section` + count + ` </span>
      </div>
</div>`

  $(this).closest('.serv-content').append(sectionContent);

});

$(document.body).on('click', 'button.js-save-section', function() {
  // get selected checkboxes's values
});


// validate checkboxes for sub items..

$(".main-content").on('change', '.js-cars-item-sub-items [type="checkbox"]', function() {
  var idx = $(this).closest('li').index(); //Get the index - Number in order
  var chk = $(this).is(":checked"); //Get if checked or not
  var obj = this; //Checkbox object

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

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

// validate checkboxes for main items.. 

$(".main-content").on('change', '.js-cars-item [type="checkbox"]', function() {
  var idx = $(this).closest('li').index(); //Get the index - Number in order
  var chk = $(this).is(":checked"); //Get if checked or not
  var obj = this; //Checkbox object
  var callerId = $(this).closest('.serv-content').attr('id');
  debugger;
  $('.main-content').find('.serv-content:not(#' + callerId + ')').each(function() {
    $(this).find('.js-cars-item').each(function() {
      //Find the checkbox with the same index of clicked checkbox. Change disabled property
      $(this).find('li:eq(' + idx + ') [type="checkbox"]').not(obj).prop("checked", false);
    });
  });

  var checkeds = [];
  $(this).closest(".serv-content").find(".js-cars-item input:checkbox:checked").each(function(index) {
    checkeds[index] = $(this).attr('id');
  });
  console.clear();
  console.log("These are checked:", checkeds);
});
.js-cars-item {
  box-sizing: content-box;
  width: auto;
  height: auto;
  padding: 10px;
  border: 3px solid red;
}

.js-cars-item-sub-items {
  box-sizing: content-box;
  width: auto;
  height: auto;
  padding: 10px;
  border: 3px solid green;
}

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

li {
  display: inline;
}

.serv-content {
  box-sizing: content-box;
  width: 250px;
  height: auto;
  padding: 10px;
  border: 5px solid blue;
}

.cars.saved {
  border-color: green;
}
<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-content">
  <div class="serv-content">
    <div class="title-content">
      <input type="text" id="name-title-1" class="name-title" value="category-1">
    </div>


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

      <div class="footer">
        <span class="num"> Section 1 </span>
      </div>
    </div>

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

</div>
<br> <br>

关于javascript - 验证 jquery 中动态生成的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50522317/

相关文章:

javascript - Node 是有状态的吗? Node能否在内存中维护变量

javascript - 在 Javascript 中查询 XML

javascript - 创建交互式 map

javascript - php 是否有内置的数组函数可以对 bool 结果进行排序/赋值?

javascript - 在 View 中使用 C# MVC 多个动态模型

javascript - 在 JavaScript 中保持两个变量值同步的最佳方法

javascript - jQuery 与插件冲突?

jquery - 如何仅在批量 getJSON 指令完成时触发某些操作?

javascript - 如何在两行 slider (滚动条)中制作 3 个缩略图

javascript - 尝试在文档就绪中生成随机背景颜色