I'm trying to figure out how to dynamically add checkboxes when the input type number is changed.
Currently, I have the following HTML code:
HTML CODE
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onkeydown="change_cb()"/>
<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">
If I change the checkbox number to 2, I want JavaScript/AJAX to add:
<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">
Similarly, if I change the checkbox number back to 1, I want it to remove one checkbox.
I previously achieved a similar functionality with tables (adding/removing rows) but in this case, I'm not sure how to add new elements (I only added new rows in my first script)...
I need assistance in writing my JS function change_cb()
EDIT TO PROVIDE MY SOLUTION
I managed to solve this issue with some help from DADE (thank you DADE):
HTML CODE (same)
<label for="cb_number">How many checkboxes ?</label>
<input id="cb_number" name="cb_number" type="number" size="1" maxlength="1" value="1">
<div class="my_cb_result"></div>
jQuery CODE
$(window).ready(function() {
$('#cb_number').on('keyup mouseup', function() {
var number = parseInt($(this).val());
$('input[type="checkbox"]').remove();
$('label[class="to_del"]').remove();
for (var i=1;i<=number;i++) {
var data = '<label for="checkbox" class="to_del">Label of my checkbox</label><input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="'+i+'">';
}
$('.my_cb_result').append(data);
});
});