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 trialdylan jasper
1,928 PointsAppending 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
231,248 PointsIf 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.
<form id="myform">
<input type="text" id="newRestaurantInput" placeholder="Add a new restaurant">
<button id="addNew">Add</button>
<form>
$('#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
1,928 PointsThanks, I figured it would have something to do with a form element!
Vitaly Khe
7,160 PointsNice!! I had the same question!