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

时间:2018-05-25 05:48:59

标签: javascript jquery

我有以下代码笔。它的作用我们可以添加Add Category,它会生成一个蓝色框,最初在类cars-item js-cars-item中嵌入了一行复选框。然后我们有不同的部分,用户可以在点击Add Section时添加多行复选框。这将嵌入到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);
    });
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

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

因此,要循环浏览其他.serv-content,我已经为您正在创建的所有id div添加了.serv-content,当您点击复选框时,我正在遍历所有div,其中包含.serv-content类,但不包含来电者的id

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

上对您的代码进行了更改
  

来自:

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

到此:

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

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

  

由此:

$(".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);
});

这是完整的代码段。

&#13;
&#13;
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);
});
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;