Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

516 LESSON 18: Using jQuery


Next is the event handler for the form, which enables users to add new items to the list:
$("#addElement").submit(function (event) {
event.preventDefault();
$("#editable").append("<li>"
+ $("#addElement input[name='liContent']").val() + "</li>");
$("#addElement input[name='liContent']").val("");
});

I bind this handler to the submit event for the form, just as I did in the previous example.
First, it prevents the form submission from completing its default action—submitting the
form to the server. Then I append the content to the list. I select the list using its ID, and
then I call the append() method, which adds the content in the argument just inside the
closing tag for the elements that match the selector. In this case, I put the value in the text
field, which I obtain using the val() method that you’ve already seen, inside an opening
and closing <li> tag, and pass that to the append() method. I also remove the content
from the text field because it has been appended to the list. Figure 18.13 shows the list
once a few elements have been added.

Finally, I allow users to remove items from the list by clicking them. There’s one trick
here. As you’ve seen, to do so I’ll need to use the click handler for the <li> elements in
the list. In this case, there’s a catch. When the page loads and the document.ready event
for the page initially fires, there are no elements in the list to bind eve nts to. Fortunately,
jQuery provides a way to set up an event handler so that it’s automatically bound to
newly created elements on the page. Here’s the code:
$(document).on('click', "#editable li", function () {
$(this).remove();
});

FIGURE 18.13
A page with items
added by a user.
Free download pdf