I have list of many checkboxes and I need to display the order of them being checked next to each other.
Something like this:
[1] checkbox
checkbox
checkbox
[2] checkbox
checkbox
[3] checkbox
Order in which they are being checked does not matter, the thing is that they need to be ordered from top to bottom as showed.
I have limited options with editing the HTML, since it is dinamically rendered, and the structure looks like this:
<td>
<label>
<input type="checkbox">
"Sample text"
</label>
</td>
<td>
<label>
<input type="checkbox">
"Sample text"
</label>
</td>
<td>
<label>
<input type="checkbox">
"Sample text"
</label>
</td>
etc.
So I have tried the following:
$('input[type=checkbox]').on('change', function(){
var number = $('input[type=checkbox]:checked').length;
$('label:has(input[type=checkbox]:checked)').text(number);
});
But it ends up replacing each label contents with 1 (not even a count).
I searched for answers here on Stackoverflow and I found the most suitable as this one:
document.querySelectorAll('td').forEach(el => {
el.innerHTML += '<span class="letter"> </span>'
})
let checkedItems=[]
document.querySelectorAll('[type=checkbox]').forEach(el => {
el.value = el.closest('label').innerText.trim()
el.addEventListener('change', e => {
let n = el.closest('label').innerText.trim();
if (!e.target.checked) checkedItems.splice(checkedItems.indexOf(n),1)
else checkedItems.push(n);
document.querySelectorAll('.letter').forEach( l=> l.innerHTML = '')
checkedItems.forEach((n,i) => {
document.querySelector(`input[value=${n}]`).closest('td').querySelector('.letter').innerHTML = i;
})
});
});
In this case I get an error caused by the input value, since it is not alphanumeric. In what way can I edit either of these in order to work? Thank you!
>Solution :
If I understood correctly that you wish to display, next to the checkbox itself, the order ( out of all checkboxes ) that a particular checkbox was checked then perhaps the following might work?
querySelectorAll can be combined with the :checked attribute selector to find the number of checked elements and this is then used within a new span element which is appeneded to the label element when the delegated event listener fires a changed event
document.addEventListener('change',e=>{
if( e.target instanceof HTMLInputElement && e.target.type=='checkbox' ){
let index=document.querySelectorAll('table [type="checkbox"]:checked').length;
let label=e.target.parentNode;
if( e.target.checked ){
let span=document.createElement('span');
span.textContent=index;
label.appendChild( span )
}else{
label.removeChild( label.querySelector('span') )
}
}
});
<table>
<tr>
<td>
<label>
<input type="checkbox">
"Sample text"
</label>
</td>
<td>
<label>
<input type="checkbox">
"Sample text"
</label>
</td>
<td>
<label>
<input type="checkbox">
"Sample text"
</label>
</td>
</tr>
</table>