I am working on my website using HTML and JavaScript. There is a webpage in it which is basically a todo list. I want to add a new todo item when the user presses the Enter key.
A new todo item should have a checkbox and a way of adding text/a title to the todo item. I tried using a textaera and adding checkboxes but their interaction wasn't happening correctly (the new checkbox automatically appearing when clicked enter wasn't happening).
I have figured out how to add the "tick" to the checkbox on click.
These checkboxes shouldn't be permanent and instead, when the user presses the backspace button, they must disappear and leave a blank line.
<textarea id="Todolist" style="height: 400px; width: 1200px"
placeholder="Enter your todolist here"></textarea>
<button name="Save" onclick="save()">Save</button>
Here is an example where I use text input elements instead of a textarea. The default behaviou when you press the Enter key in an input element is to submit the form. In this case we need to prevent that and add a new todo item instead.
If you remove all styling from the input it looks like it is free text input with the Enter and Backspace keys adding and removing "lines".
document.forms.form01.addEventListener('keydown', e => {
switch(e.key) {
case 'Enter':
e.preventDefault();
if(e.target.name == 'title'){
add_item(e.target.form);
}
break;
case 'Backspace':
if(e.target.name == 'title' && e.target.value == ''){
e.preventDefault();
remove_item(e.target);
}
break;
}
});
function add_item(form){
// create the new todo item
let fs = document.createElement('fieldset');
let cb = document.createElement('input');
cb.name = 'item';
cb.type = 'checkbox';
fs.append(cb);
let tb = document.createElement('input');
tb.name = 'title';
tb.type = 'text';
fs.append(tb);
// add the todo item to the items fieldset
form.items.append(fs);
// set focus to the new text input
tb.focus();
}
function remove_item(input) {
let fs = input.closest('fieldset');
// find the previous element
let prev_fs = fs.previousElementSibling;
// if there is a rev_fs set focus to the input
// in the previous text input.
// and delete the todo item/fieldset
if(prev_fs){
prev_fs.elements.title.focus();
fs.remove();
}
}
fieldset {
border: none;
margin: 0;
padding: 0;
}
input[type="text"] {
border: none;
}
input[type="text"]:focus {
outline: none;
}
<form name="form01">
<fieldset name="items">
<fieldset>
<input type="checkbox" name="item"><input type="text" name="title">
</fieldset>
</fieldset>
<button type="submit">Save</button>
</form>