HTML and CSS Reference
In-Depth Information
I'll start with the markup for the page. First, I need a list. In this example, the user will
be able to add elements to the list and remove elements from the list. All I need is an
empty list with an ID:
<ul id=”editable”>
Next, I have a form that enables users to add a new item to the end of the list. It has a
text input field and a Submit button:
<form id=”addElement”>
<label> New list item: <input name=”liContent” size=”60” /></label>
<input type=”submit” value=”Add Item” />
And finally, I've added a link that removes all the elements the user has added to the list:
<p><a id=”clearList” href=”#”> Clear List </a></p>
The action is on the JavaScript side. Let's look at each of the event handlers for the page
one at a time. First, the event handler for the Clear List link
$(“#clearList”).click(function (event) {
This event handler prevents the default action of the link (which would normally return
the user to the top of the page) and calls the empty() method on the list, identified by
selecting its ID. The empty() method removes the contents of an element.
Next is the event handler for the form, which enables users to add new items to the list:
$(“#addElement”).submit(function (event) {
+ $(“#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 selected the list using its ID,
and then I call the append() method, which adds the content in the argument just inside
Search WWH ::

Custom Search