vendredi 24 mai 2019

All Checkboxes prop checked but I only want ONE checkbox to be triggered

I have list of items that can be "add to favorite", in this case I use checkbox, so user can check the checkbox to add to favorite, and vice versa, uncheck the checkbox to remove from favorite.

The flow suppose to be like this:

  1. When the checkbox is unchecked, and user click on it, it will be checked

  2. When the checkbox is checked, and user click on it, it will trigger a modal which ask them to confirm if they really want to remove the item from favorite. In the pop up modal, there is a confirm button, and when user click on it, it will uncheck the checkbox and close the pop up modal.

Below are the html element

    <div class="star_wrap">
      <input type="checkbox" /><label onclick="confirmLabelRemove(this)"><label>
    </div>
    i put the click event in label to trigger the input before it to be checked or unchecked

Below are the code to generate the unique ID for each checkbox

    var listItems = $(".star_wrap"); // the container of each checkbox
    listItems.each(function (idx) {
    $(this).find('input').attr('id', 'chkbox' + idx);
    //$(this).find('label').attr('for', 'chkbox' + idx); I don't want this 
    feature because If I click on the label it will prop check the 
    checkbox before the pop up modal show up.
});

Below are the code to trigger prop check event

    function confirmLabelRemove(obj) {
    var thisLabelInput = $(obj).prev(); // find the input before the label

    if ($(thisLabelInput).is(':checked')) {
    overlayConfirmShow(); // transparent layer to prevent back content clickable
    $('.confirmation_box').addClass('show'); // show the pop up modal

    $('#confirmBoxConfirm').on('click', function () {
        $(obj).prev().prop('checked', false);
        $(obj).closest('.grid-item').addClass('unfav');
        overlayConfirmHide();
        $('.confirmation_box').removeClass('show');
     });
    } else {
      $(obj).closest('.grid-item').removeClass('unfav');
      $(obj).prev().prop('checked', true);
     }
    }

If there is only 1 checkbox, it works perfectly fine. But when they are a list of checkboxes, Unchecking and checking 1 of the checkbox will trigger previously checked or unchecked checkboxes. Please advice, thanks.




Aucun commentaire:

Enregistrer un commentaire