Know which checkboxes are checked

First, we need to select all the checkbox. In jQuery, this is done by selecting input[type="checkbox"].

Second, we need to know a checkbox is checked and unchecked. We can listen to the change event of the checkbox.

Third, the checkboxes are created programatically, so we need to use the jQuery delegate method to register all checkboxes for the change event.

Forth, we want to select all checked checkbox. We can do this with the jQuery selector $('input[type="checkbox"]:checked'). This selects all the checked checkboxes into a jQuery array.

Last, we want the value of the checkboxes as an array. (Instead of the checkboxes themselves). We can do that by map method.

So here is the code that listen to all (including future) checkboxes’ change event and get a list of tags from the checked ones.

1app.view.tagList.delegate('input[type="checkbox"]', 'change', function(){
2  // get all checked tags
3  var checkedTags = $('input[type="checkbox"]:checked').map(function(){
4    return $(this).val();
5  });
6  console.log(checkedTags));
7});

We have the array of checked tag names. What we want is that we can re-render the book list with the giver checked tags. The final call in this event handle should be the following.

1app.view.tagList.delegate('input[type="checkbox"]', 'change', function(){
2  // get all checked tags
3  var checkedTags = $('input[type="checkbox"]:checked').map(function(){
4    return $(this).val();
5  });
6  app.view.renderList(app.data.findBooksByTags(checkedTags));
7});

Yes, we haven’t implement the findBooksByTags at all. We designed what we want finally and the we go to the data object to implement it.

What’s next? We’re going to take a look at “Adding the ISBNs to tag data”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content