In this instance, it's possible to do this without JavaScript, just use the :checked
pseudo class:
EXAMPLE HERE
#mname {
display:none;
}
#maidenname:checked ~ #mname {
display:block;
}
Use either the general sibling combinator, ~
, or the adjacent sibling combinator +
, to change the display of the input
element when the checkbox element is toggled. This of course assumes that the checkbox precedes the input element in the DOM.
If you would rather use JavaScript, you could use the following:
JS EXAMPLE HERE
var checkbox = document.getElementById('maidenname');
var input = document.getElementById('mname');
checkbox.addEventListener('click', function () {
if (input.style.display != 'block') {
input.style.display = 'block';
} else {
input.style.display = '';
}
});
Alternatively, if you would rather add an input
element to the DOM (as your title implies), rather than changing the visibility of it, you could use something like this:
ALTERNATIVE JS EXAMPLE HERE
var checkbox = document.getElementById('maidenname');
checkbox.addEventListener('click', function () {
if (document.getElementById('mn')) {
document.getElementById('mn').remove();
} else {
var input = document.createElement("input");
input.id = 'mn';
input.type = 'text';
input.placeholder = 'Maiden Name';
document.body.appendChild(input);
}
});