kmgiffin
kmgiffin

Reputation: 39

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();
    }

});

});

Upvotes: 2

Views: 54

Answers (2)

cFreed
cFreed

Reputation: 4482

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're appending 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.

Upvotes: 3

Radmation
Radmation

Reputation: 1534

I think this is what you are going for?

$('button').on('click', function() {

    var a = $('#first-contact').val().toLowerCase();

   // update here
    $('#list-section').append("<p><input type='checkbox' value='"+a+"'></p>");

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

});

Upvotes: 1

Related Questions