I am trying to build a simple web page that dynamically creates a row of checkboxes. First, I figured out how to put the checkboxes in a single row:
.checkbox-inline {
display: inline-block;
}
<form role="form" method="post">
<legend>What is Your Favorite Pet?</legend>
<label class="checkbox-inline">
<input type="checkbox" name="cbpets[]" value="Cats">
Cats
<br>
</label>
<label class="checkbox-inline">
<input type="checkbox" name="cbpets[]" value="Dogs">
Dogs
<br>
</label>
</form>
Next, I found this page StackOverflow question (see first answer) and was able to create the checkboxes, but across multiple rows. Now I am stuck. I am trying to put the checkboxes in one row, but have not figured how. I tried adding (using the syntax in the stackoverflow answer)
var color = document.createElement("input");
color.setAttribute(
'style',
'class="checkbox-inline"',
);
But this didn’t work. Anything else you can suggest that I try?
You don't need to use display: inline-block; to force all checkbox in oneline.
Just remove <br> tag in your label and then all checkbox will be displayed in one line.
<form role="form" method="post">
<legend>What is Your Favorite Pet?</legend>
<label class="checkbox-inline"><input type="checkbox" name="cbpets[]" value="Cats">Cats</label>
<label class="checkbox-inline"><input type="checkbox" name="cbpets[]" value="Dogs">Dogs</label>
</form>
You don't have to do any CSS styling for this as the inputs will default to inline anyway.
Add your pets to an array, loop over the array and create some inputs, and then add the result of all those inputs to the DOM.
// Cache the container element
const container = document.querySelector('.container');
// Define the pets
const pets = ['Dog', 'Cat', 'Moose', 'Barbary macaque', 'Snail'];
// Temporary array to hold the input strings as
// we build them in the loop
const html = [];
// Loop over the pets array, create a new
// HTML string for each of them, and push that string
// into our temporary array
for (const pet of pets) {
const input = `
<label>
${pet}
<input type="checkbox">
</label>
`;
html.push(input);
}
// Add the completed HTML array to the container
// by `joining` all the elements into one string
container.insertAdjacentHTML('beforeend', html.join(''));
.legend { margin-right: 0.5em; font-weight: 700; }
<div class="container">
<span class="legend">What is Your Favorite Pet?</span>
</div>
Additional documentation