You have one main problem with your code in your question:
$("#chk").on("change",function(){
$("#chk").append('<input type="text" />');
});
The problem is that an <input>
is a void element:
A void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes.
The following is a complete list of the void elements in HTML:
area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr
Citation: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements, accessed 01:00, 2015-11-23.
Because jQuery – almost always – fails silently it never alerts you to the fact that you're trying to achieve the impossible (literally: the impossible); so instead you have to append the elements elsewhere, such as after (or before) the given element.
// bind the anonymous function of the
// on() method to handle the change
// event of the '#chk' element:
$('#chk').on('change', function() {
// on the assumption you only want
// to append elements when the element
// is in fact checked:
if (this.checked) {
// creating the <input> element:
$('<input />', {
// setting its 'type' attribute/property:
'type': 'text',
// setting its 'placeholder' attribute:
'placeholder': 'input number: ' + $('input[type=text]').length
// inserting the <input> after the '#chk' element:
}).insertAfter(this);
}
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<!-- I removed the irrelevant HTML -->
<label>Click to add a new input element (when checked):
<input type="checkbox" id="chk">
</label>
</div>
As you can see when you check the check-box this appends the new <input>
directly after that check-box. Since I don't expect that's what you want to do, I'd suggest amending the above, to access the parent – <div>
– element:
// bind the anonymous function of the
// on() method to handle the change
// event of the '#chk' element:
$('#chk').on('change', function() {
// on the assumption you only want
// to append elements when the element
// is in fact checked:
if (this.checked) {
// creating the <input> element:
$('<input />', {
// setting its 'type' attribute/property:
'type': 'text',
// setting its 'placeholder' attribute:
'placeholder' : 'input number: ' + $('input[type=text]').length
// appending the <input> element to the parentNode of the
// '#chk' element:
}).appendTo(this.parentNode);
}
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<!-- I removed the irrelevant HTML -->
<label>Click to add a new input element (when checked):
<input type="checkbox" id="chk">
</label>
</div>
References: