mercredi 1 mars 2017

dynamically adding items to table, want to select checked checkboxes and move

I am creating a basic to do app using jQuery and Bootstrap. This is the current code that I have written:

HTML:

<div class="container">

    <h1 class="center">To Do List</h1>

    <div class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <div class="input-group">
                    <input type="text" class="form-control" id="searchInput" placeholder="Add a new item">
                    <span class="input-group-btn">
                        <button type="button" class="btn btn-success" id="addItemBtn">Add</button>
                    </span>
            </div><!-- ./input-group -->
        </div> <!-- ./col-sm-4 col-sm-offset-4 -->
    </div><!-- ./row -->

    <div class="row">

        <div class="col-sm-6">
            <h3 class="center">To Do:</h3>
            <table class="table table-striped">
                <tbody id="toDoList">
                 <!-- Items added here -->
                </tbody>
            </table>
        </div> <!-- ./col-sm-6 -->

        <div class="col-sm-6">
            <h3 class="center">Completed:</h3>
            <table class="table table-striped">
                <tbody id='completedItems'>
                    <div id='log'></div>
                    <!-- COMPLETED ITEMS TO BE ADDED -->
                </tbody>
            </table>
        </div> <!-- ./col-sm-6 -->

    </div> <!-- ./row -->
</div> <!-- ./container -->

I have been successful in dynamically adding user input into the "To Do" section with the following jQuery:

jQuery:

let toDoArr = [];

$('#addItemBtn').click(() => {
    let item = $('#searchInput').val();
    toDoArr.push(item);
    $('#toDoList').append('<tr><td class="listText"><label for=' + item + '>' + item + '</label><input type="checkbox" value=' + item + '></td></tr>');
    $('#searchInput').val('');
});

This code adds the items successfully, but for some reason, I cannot grab the items that are selected with the checkbox. I have tried $('input[type=checkbox]').click(function() { $('input:checked') ... } and the many other variations of such and even tried to simply have the page alert when a checkbox is checked, to no avail.

I was under the assumption that bootstrap automatically detected if a checkbox is checked and added the 'checked' attribute, however, I am wondering if because I am adding it dynamically if that functionality breaks?

In the end, I am looking to move the items when completed (aka when the checkbox is checked) over to the "completed" section in a similarly dynamic way as above, while splicing the item from the toDoArr and pushing it into a new array (which I can do). Why can't I grab the item that had the checked checkbox?




Aucun commentaire:

Enregistrer un commentaire