kmgiffin kmgiffin - 4 months ago 9
Javascript Question

trying to add a checkbox dynamically with jquery but nothing apepars

Just trying to create a very basic to-do app and for whatever reason, my checkboxes are not showing up.

html:

<div class="todo-box">
<input id="first-contact" type="text" placeholder="what do you have to do?"></input>
<button>submit</button>
<div id="list-section">
</div>
</div>


and jquery:

$( document ).ready(function() {

$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
$('<p>').attr('class', 'list-item').append(a).appendTo('#list-section');
$('<input>', {type: "checkbox"}).appendTo('#list-item');

var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}

});


});

Answer

You have 2 issues in $('<input>', {type: "checkbox"}).appendTo('#list-item');:

  • you're using {type: "checkbox"} at the place where jQuery $() expects a domain argument: you must build a complete element in first argument instead
  • you append the element to a list-item id while you created it as a class

This will work:

$( document ).ready(function() {

$('button').on('click', function() {
    var a = $('#first-contact').val().toLowerCase();
    $('<p>').attr('class', 'list-item').append(a).appendTo('#list-section'); 
    $('<input type="checkbox">').appendTo('.list-item:last');

    var pAmount = $('#list-section').children().length;
    if (pAmount > 6) {
        $('#list-section p').last().remove();
    }

});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="todo-box">
    <input id="first-contact" type="text" placeholder="what do you have to do?"></input>
    <button>submit</button>
    <div id="list-section">
    </div>
</div>

EDIT: modified in response to the OP's comment : added :last modifier to make checkbox added to the just newly created item only.