Append to body



$(document).ready(function() {
$('#button').click(function() {
var toAdd = $('input[name=checkListItem]').val();


I don't know how to exacly do this


You have a good start. The value in toAdd will be a string, the text typed into the form control. Now we need to construct a DIV and insert it into the DOM.

Look for the container element in the HTML source listing. What is the class name? list?

To create an element we use jQuery object syntax with some HTML in a string.

 var $item = $('<div class="item">` + toAdd + '</div>');

This is not exactly what we need, though. Just an example of creating an element. It is now in memory and recallable.


However, this will not be accepted by the lesson checker. What we need is to construct the element in the argument to .append().

$('.list').append('<div class="item">' + toAdd + '</div>');


Extra Study

Once you get through this module and are a little more comfortable with the concepts, give this code a try in the lesson interface. I'll explain it afterward.

  var $input, $item, toAdd;
  $input = $('input[name=checkListItem]');
  $item = $('<div class="item"/>');
    toAdd = $input.val();

The first line declares all the variables we will be using. They are in parent scope of the handler, so can be accessed inside the function.

The second line caches the page element as a jQuery object. We can query this object repeatedly.

The third line creates a jQuery object of a DIV element. It is only in memory at this point, but we can clone it and insert text in our handler.

The fourth line runs the focus method on our cached input element. As soon as the program starts we can type immediately in the form without having to click in it. Use the Add button, not Enter when using this form. Enter will give a blank screen. Can explain further if you need to know why.

Inside the click handler, we copy the current form value to our variable in the first line.

The second line is where all the magic happens. To our list object we append a clone of the $item object, populated with the text stored in our variable.

The last line clears the input field and restores focus so we can just type, click Add, type some more, click Add, and so on.

This will not pass the lesson, so expect to see the SCT error message. You can ignore it. I've posted this to give some insight into some of the powerful features in jQuery. The concepts are actually valid JavaScript approaches, not confined to jQuery only. In vanilla JS we would use a similar approach, advance declaration of variables, caching objects that are repeatedly called upon such as page elements and code templates, and cloning of stored objects. All these concepts are easier to understand and use with practice and experimentation.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.