1

I have a small issue. I have a main category that consists of a row of checkboxes. In this main category, I have a button Add Section, which adds another row of checkboxes under the above row and keep adding another row of checkboxes after each click on the Add Section.

Outside the box, I have a main button that allows adding another main category. The principle is the same, it adds a row of checkboxes, followed by another section button. And if I want to add another row again in this category, I just click on the Add Section button.

The issue is I am having, I am unable to add another row on clicking the Add section button. Also, I want to validate the as from the second row checkboxes and ownwards, such that if I check the first checkbox in the second row, I should be able to check the first checkbox in the third row.

The first row of checkboxes in the main category is independent of the second row of checkboxes and the onwards rows (that is the rows created on adding a section

I have done the validation as in : https://jsfiddle.net/fL3hekhw/

EDITED

The demo is : https://jsfiddle.net/fL3hekhw/

When I click on Add Section button in a box, it should not duplicated the added checkboxes in other boxes. How can I prevent this ? Please help.

Can someone please help me with this ? I am totally stuck.

ExpertGenie
  • 195
  • 3
  • 14

2 Answers2

2

There are a few issues with the demo you linked to.

  1. You were asking for .closest('.js-cars-items') but you only used .js-cars-item as a class
  2. When you added new checkboxes you were re-using ids, which must be unique across the whole document
  3. When you were adding new categories, you were not registering the 'change' event listener with the new .cars element that you appended

I've made a few minor refactorings that I hope make the code a bit easier to read. I also removed the troublesome .closest('.js-cars-items') call completely because you were already iterating over .js-cars-item anyway.

I'm only unsure about one thing, though. Do you want checkboxes in a column to be validated across all categories or per category?

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>
Rajit
  • 808
  • 5
  • 9
  • I do not want to add validation on the first row of the checkboxes. How can I achieve that ? Thank you. – ExpertGenie May 20 '18 at 17:18
  • Why don't you just remove the `js-cars-item` class from the first row? I don't think this was part of your question — if you do have further questions people might be able to answer small things here but do also consider opening a new question. And if you're happy with the above answer _to the question you asked_ please do accept it. – Rajit May 20 '18 at 17:22
0

I'm not sure but I suspect the problem comes from not catching the click event on created buttons, right?

If you want to listen to events on elements that are added after document load, don't use .change() but use $(document).on('eventName', 'elementName', callbackFunction);

Read more here:

Event handler not working on dynamic content

Michael Beeson
  • 2,840
  • 2
  • 17
  • 25
  • The demo is : https://jsfiddle.net/fL3hekhw/ When I click on Add Section button in a box, it should not duplicated the added checkboxes in other boxes. How can I prevent this ? Please help. – ExpertGenie May 20 '18 at 11:28
  • In your demo there is no "Add section" button. What I mentioned in this answer will still be important for once you've implemented the button. Also you'll have to make the .change() function only deal with checkboxes within the section - you can do this using the correct selector. As it is, you'll be looping through all checkboxes – Michael Beeson May 20 '18 at 14:27