Select one checkbox at a time from group of checkbox

Select one checkbox at a time from group of checkbox



<div class="btn-group" role="group" onclick="selectOne(event)">

  <input type="checkbox" class="btn-check" id="btncheck1" value='1' autocomplete="off">

  <label class="btn btn-outline-primary" for="btncheck1">Checkbox 1</label>

  <input type="checkbox" class="btn-check" id="btncheck2" value='2' autocomplete="off">

  <label class="btn btn-outline-primary" for="btncheck2">Checkbox 2</label>

  <input type="checkbox" class="btn-check" id="btncheck3" value='2' autocomplete="off">

  <label class="btn btn-outline-primary" for="btncheck3">Checkbox 3</label>

</div>

<script>

function selectOne(event) {

    const clickedElement = event.target;


    if (clickedElement.matches('.btn-check')) {

        const checkboxes = document.querySelectorAll('.btn-check');

        checkboxes.forEach((checkbox) => {

            checkbox.checked = false; 

            checkbox.removeAttribute('checked'); 

            if (checkbox === clickedElement) {

                checkbox.checked = true; 

                checkbox.setAttribute('checked', 'checked');

                const selectedValue = checkbox.value;                

            }

        });

    }

}

</script> 

Comments

Popular posts from this blog

How to Delete record using PHP Ajax

How to seperate character from string in php