Reputation: 145
I'm creating a Chrome Extension such that the user can create a todo list. I want to make it so that once a user types out a task, the user can press the "Enter" key to submit it. This will cause the task to go down to the next line. I'm having trouble allowing the user to make the task go onto the next line.
HTML:
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li>test</li>
</ul>
Javascript:
$(() => {
$('#newtask').on('keydown', (e) => {
if(e.keyCode == 13){
???
}
});
});
Upvotes: 0
Views: 3203
Reputation: 84
I think you want your list to contain the text entered by user? You can use the jQuery append method to achieve that.
$('#newtask').keydown(function(e){
if (e.which == 13) {
//Construct some html to append:
var newLi = "<li>" + $('#newtask').val() + "</li>";
$('#tasksUL').append(newLi);
}
});
Try my JS Fiddle implementation
Upvotes: 0
Reputation: 974
With vanilla javascript you just add an eventListener
to the actual input element
listening for keydown
events.
let tasks = document.getElementById('tasksUL');
document.getElementById('newtask').addEventListener('keydown', (e) => {
if(e.key == 'Enter'){
let new_item = document.createElement('li');
new_item.innerText = e.target.value;
tasks.appendChild(new_item);
}
});
Upvotes: 1
Reputation: 7901
Attach keypress
eventlistener to input
element, not to ul
. If the key pressed is enter, get the content of input element, create new li
element and set it's text with the inputted value, append to ul
and then clear the input
element.
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
$('#tasksUL').append(`<li>${newTask}</li>`);
$(this).val("");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li>test</li>
</ul>
Upvotes: 2