Write jQuery code to add a new list item from a text field

Description: When the user clicks “Add”, the text of the input must be added as a new list item, and the input must be cleared. Do not add empty text.

Hint:

  • Use .val(), $('<li>').text(...) and .append().

HTML of the page

<input type="text" id="task" value="Buy milk">
<button id="add">Add</button>
<ul id="todo"></ul>

Solution

$('#add').on('click', function () {
  var text = $('#task').val().trim();

  if (text === '') {
    return;
  }

  $('<li>').text(text).appendTo('#todo');
  $('#task').val('');
});

$('#add').click();
HTML after the code runs

<input type="text" id="task" value="Buy milk">
<button id="add">Add</button>
<ul id="todo">
<li>Buy milk</li>
</ul>

How it works

  • trim() removes spaces, so an empty text is not added.
  • We create the li and set the text with .text(), which is safe against HTML in the input.
  • .val('') clears the field.

Read Add Elements.


Learn more about the similar topics:
Tutorials
jQuery Get Content and Attributes
jQuery Set Content and Attributes
jQuery Add Elements: append, prepend, after, before
jQuery Remove Elements: remove, empty, detach
jQuery CSS Classes: addClass, removeClass, toggleClass
jQuery CSS Methods
jQuery Dimensions and Position
Exercises & Assignments
Write jQuery code to change the text of a heading when the page loads
Write jQuery code to change the color and size of all paragraphs
Write jQuery code to add a new list item from a text field
Interview Questions & Answers
What is the difference between text(), html() and val() in jQuery?
What is the difference between attr() and prop() in jQuery?
How do you add, remove and toggle a class in jQuery?
What is the difference between remove(), empty() and detach() in jQuery?
What is the difference between append(), prepend(), after() and before()?
What is the difference between data() and attr(‘data-*’) in jQuery?
What is the difference between width(), innerWidth() and outerWidth() in jQuery?