javascript programmatically add label to checkbox code example
Example 1: add checkbox dynamically in javascript
$(document).ready(function() {
$('#submit').click(function() {
var list = ['Car', 'Bike', 'Scooter'];
for (var value of list) {
$('#container')
.append(`<input type="checkbox" id="${value}" name="interest" value="${value}">`)
.append(`<label for="${value}">${value}</label></div>`)
.append(`<br>`);
}
})
});
Example 2: javascript create checkbox with label
const inputActiveElement = document.createElement('input');
inputActiveElement.classList.add('mr-2');
inputActiveElement.id = `active_image`;
inputActiveElement.type = 'checkbox';
inputActiveElement.value = '123';
inputActiveElement.name = 'active_image[]';
inputActiveElement.setAttribute('checked','true');
const labelActiveElement = document.createElement('label');
labelActiveElement.setAttribute('for',`active_image`);
labelActiveElement.innerText = 'Active';
const divInnerElement = document.createElement('div');
divInnerElement.classList.add('form-inline');
divInnerElement.classList.add('mt-2');
divInnerElement.append(inputActiveElement, labelActiveElement);