Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript One Solution

dylan jasper
dylan jasper
1,928 Points

Appending data to the list with click event and keypress event

In the exercise we are asked to append an item to a list when a user clicks on a button. That is solved with something like the following: $('#addNew').on('click', function(){ const newItem = $('#newRestaurantInput').val(); $('ul').append(<li>${newItem}</li>); });

However in a real scenario many users would likely attempt to submit by clicking pressing enter on the keyboard. I wrote the following code to take that into account:

$('input[type="text"]').keypress(function(e) { if (e.which === 13) { let newItem = $(this).val(); $('ul').append(<li>${newItem}</li>); } });

My question is if there is a way I can improve this instead of having two different functions?

3 Answers

Steven Parker
Steven Parker
229,771 Points

If you enclose both the input box and the button in a "form" element, you could create a handler for the submit event of the form element. It would be generated for both the button click and to the enter key used in the text box.

index.html
<form id="myform">
  <input type="text" id="newRestaurantInput" placeholder="Add a new restaurant">
  <button id="addNew">Add</button>
<form>
app.js
$('#myform').on('submit', function(e) {
  e.preventDefault();  // use this so the form doesn't try to reload the page
  const newRestaurant = $('#newRestaurantInput').val();
  $('ul').append(`<li>${newRestaurant}</li>`);
 });
dylan jasper
dylan jasper
1,928 Points

Thanks, I figured it would have something to do with a form element!

Vitaly Khe
Vitaly Khe
7,160 Points

Nice!! I had the same question!