I'm creating a Chrome Extension that allows the user to create a todo list. So far I am able to type in a task and submit it. Now I want this input, which is a list, to have a checkbox. Right now, whenever the user submits a task, it is counted as a list.
HTML:
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li><input type="checkbox"><label>test</label></li>
</ul>
Javascript:
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
const li = document.createElement('li');
li.textContent = newTask;
$('#tasksUL').append(li);
$(this).val("");
}
}
});
});
try this...
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
var li = $("<li><input type='checkbox'<label>" + newTask + "</label></li>");
$('#tasksUL').append(li);
$(this).val("");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li><input type="checkbox"><label>test</label></li>
</ul>
add child to li,just like above you done.
const input=document.createElement('input')
input.type="checkbox"
li.append(input)
Well, by the way you're doing, you'll first have to create the input checkbox and its label and then add it to the list.
Here is an example with your code: https://codepen.io/pedrovsn/pen/ZdqrGw
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
const label = document.createElement('label')
label.innerText = newTask;
const checkbox = document.createElement('input');
checkbox.name = 'checkbox';
checkbox.type = 'checkbox';
checkbox.value = newTask;
const li = document.createElement('li');
li.appendChild(checkbox);
li.appendChild(label);
$('#tasksUL').append(li);
$(this).val("");
}
}
});
});
Related
I am a new learner and I am facing a problem. I want to create a simple messaging app and I want that if there is no text inside the input field then the button should be disabled. Help me out.
Here is the code:
let sendMessage = document.getElementById("sendMessage");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
if (val.value === "") {
sendMessage.disabled = true;
} else {
sendMessage.disabled = false;
}
});
<div id="messages"></div>
<input type="text" id="val" />
<button id="sendMessage">Send</button>
You should use input event to set disabled to false or true. Set disabled to true by default and after button was clicked.
let sendMessage = document.getElementById("sendMessage");
let input = document.getElementById("val");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
sendMessage.disabled = true;
});
input.addEventListener("input", () => {
if(input.value.length > 0){
sendMessage.disabled = false;
} else {
sendMessage.disabled = true;
}
});
<body>
<div id="messages"></div>
<input type="text" id="val"/>
<button id="sendMessage" disabled>Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Simply create a disabled class for the button if you use custom button.
Then listen to the input change and toggle the class on button if the input have value.
With your code :
const button = document.getElementById('sendMessage');
const input = document.getElementById('message-input');
const messagesBox = document.getElementById('messages');
input.addEventListener('input', () => sendMessage.disabled = input.value === '');
button.addEventListener('click', () => {
let p = document.createElement('p');
let pTxt = document.createTextNode(input.value);
p.appendChild(pTxt);
messagesBox.appendChild(p);
});
<body>
<div id="messages"></div>
<input type="text" id="message-input" />
<button id="sendMessage" disabled >Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Set a keyup input handler for the input field and a click handler for the button. In the snippet event delegation is used.
document.addEventListener(`input`, handle);
document.addEventListener(`click`, handle);
function handle(evt) {
const isInput = evt.target.closest(`#val`);
const isBttn = evt.target.closest(`#sendMessage`);
if (isInput) {
document.querySelector(`#sendMessage`).disabled = !isInput.value.trim();
}
if (isBttn) {
isBttn.disabled = isBttn;
const inputField = document.querySelector(`#val`);
document.querySelector(`#messages`).insertAdjacentHTML(`beforeend`,
`<li>${inputField.value.trim()}</li>`);
inputField.value = ``;
inputField.focus();
}
}
<ul id="messages"></ul>
<input type="text" id="val" />
<button id="sendMessage" disabled>Send</button>
I am working on "to do list" using Vanilla JavaScript and stuck with edit button.
This is what I have done so far.
// console.log("Hello from inside");
const input = document.getElementById("inputText");
const display = document.getElementById("display");
const displayDone = document.getElementById("display-done");
const button = document.getElementById("addButton");
const deleteAll = document.getElementById("delete-icon");
// const ul = document.getElementById("display");
// Create and Remove list item
function createItem() {
let listItem = document.createElement("li");
listItem.className = "create";
listItem.appendChild(document.createTextNode(input.value));
display.appendChild(listItem);
input.value = "";
let editButton = document.createElement("button");
editButton.innerText = "edit";
editButton.className = "edit";
editButton.addEventListener("click", (e) => {
//console.log(e.currentTarget.parentNode);
// 1. When edit button is clicked, change list item to be an input text. <input type="text" value="my to do task"/>
// 2. Change edit button to be something like "complete" button
editButton.innerText = "complete";
// 3. When complete button is clicked, change the input item to be a list item again with the updated text.
editButton.addEventListener("click", (e) => {
editButton.innerText = "edit";
});
});
let removeTask = document.createElement("input");
removeTask.setAttribute("type", "button");
removeTask.setAttribute("value", "X");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener("click", (e) => {
listItem.parentNode.removeChild(listItem);
});
listItem.appendChild(editButton);
listItem.appendChild(removeTask);
listItem.addEventListener("dblclick", (e) => {
displayDone.appendChild(listItem);
listItem.style.backgroundColor = "#54e346";
listItem.style.textDecoration = "line-through";
editButton.style.display = "none";
});
}
//Make sure user fill the input
function addAfterClick() {
if (input.value.length > 0) {
createItem();
} else {
alert("Write something mate!");
}
}
//List item can be added with "Enter" as well
function addWithEnter(event) {
if (event.keyCode === 13) {
addAfterClick();
}
}
// Remove all with user approve
function removeAll(event) {
let answer = prompt(`Type "Delete All" If you are that sure!`);
if (answer === "Delete All") {
display.style.display = "none";
location.reload();
} else {
alert("Try One More Time");
}
}
//Event Listeners
button.addEventListener("click", addAfterClick);
input.addEventListener("keyup", addWithEnter);
deleteAll.addEventListener("click", removeAll);
<div class="main-container">
<h2 class="title">to do list <i class="fas fa-pencil-alt"></i></h2>
<div class="content">
<input
id="inputText"
type="text"
placeholder="Add to your list..."
maxlength="20"
/>
<i id="addButton" class="fas fa-plus"></i>
<div class="remove-container">
<i id="delete-icon" class="far fa-trash-alt"></i>
<p id="remove-text">Delete All</p>
</div>
<ul id="display"></ul>
</div>
<div class="completed">
<h2 class="title-done">
completed tasks <i class="far fa-check-circle"></i>
</h2>
<ul id="display-done"></ul>
</div>
</div>
What I want to do it;
When edit button is clicked, change list item to be an input text.
Change edit button to be something like "complete" button
When complete button is clicked, change the input item to be a list item again with the updated text.
I have tried ChildNode.replaceWith() but did not work. Am I on the right path? and also what direction(s) I should follow. Thanks in advance!
My approach is to add an input field everytime you create an item:
at initial insertion hide the input field
on click on the edit button show the input and change the textNode
after you editing
console.log("Hello from inside");
const input = document.getElementById("inputText");
const display = document.getElementById("display");
const displayDone = document.getElementById("display-done");
const button = document.getElementById("addButton");
const deleteAll = document.getElementById("delete-icon");
// const ul = document.getElementById("display");
// create edit input and hide the input at first
const editInput=document.createElement("input");
editInput.setAttribute("hidden",true);
// eventhandler for editInput
function editItem(e,item){
// remove the current text node
e.target.parentNode.removeChild(e.target.parentNode.childNodes[0])
// insert at the beginning of the childNodes
e.target.parentNode.prepend( e.target.value)
e.target.setAttribute("hidden",true)
}
// Create and Remove list item
function createItem() {
let listItem = document.createElement("li");
listItem.className = "create";
listItem.appendChild(document.createTextNode(input.value));
display.appendChild(listItem);
input.value = "";
let editButton = document.createElement("button");
editButton.innerText = "edit";
editButton.className = "edit";
editInput.value=""
editButton.addEventListener("click", (e) => {
// 1. When edit button is clicked, change list item to be an input text. <input type="text" value="my to do task"/>
// 2. Change edit button to be something like "complete" button
// appended edit input
listItem.append(editInput)
if(e.target.innerText === "edit"){
editInput.removeAttribute("hidden",false)
e.target.innerText = "complete";
}else{
e.target.innerText = "edit";
}
// add the event handler for the Editinput
editInput.addEventListener("change",(e)=>editItem(e,listItem));
editInput.value=""
// 3. When complete button is clicked, change the input item to be a list item again with the updated text.
});
let removeTask = document.createElement("input");
removeTask.setAttribute("type", "button");
removeTask.setAttribute("value", "X");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener("click", (e) => {
listItem.parentNode.removeChild(listItem);
});
listItem.appendChild(editButton);
listItem.appendChild(removeTask);
listItem.addEventListener("dblclick", (e) => {
displayDone.appendChild(listItem);
listItem.style.backgroundColor = "#54e346";
listItem.style.textDecoration = "line-through";
editButton.style.display = "none";
});
}
//Make sure user fill the input
function addAfterClick() {
if (input.value.length > 0) {
createItem();
} else {
alert("Write something mate!");
}
}
//List item can be added with "Enter" as well
function addWithEnter(event) {
if (event.keyCode === 13) {
addAfterClick();
}
}
// Remove all with user approve
function removeAll(event) {
let answer = prompt(`Type "Delete All" If you are that sure!`);
if (answer === "Delete All") {
display.style.display = "none";
location.reload();
} else {
alert("Try One More Time");
}
}
//Event Listeners
button.addEventListener("click", addAfterClick);
input.addEventListener("keyup", addWithEnter);
deleteAll.addEventListener("click", removeAll);
<div class="main-container">
<h2 class="title">to do list <i class="fas fa-pencil-alt"></i></h2>
<div class="content">
<input
id="inputText"
type="text"
placeholder="Add to your list..."
maxlength="20"
/>
<i id="addButton" class="fas fa-plus"></i>
<div class="remove-container">
<i id="delete-icon" class="far fa-trash-alt"></i>
<p id="remove-text">Delete All</p>
</div>
<ul id="display"></ul>
</div>
<div class="completed">
<h2 class="title-done">
completed tasks <i class="far fa-check-circle"></i>
</h2>
<ul id="display-done"></ul>
</div>
</div>
just a suggestion. you can use an input element for each item.
const input = document.getElementById("inputText");
const display = document.getElementById("display");
const displayDone = document.getElementById("display-done");
const button = document.getElementById("addButton");
const deleteAll = document.getElementById("delete-icon");
const createEditBtn = () => {
const editButton = document.createElement("button");
editButton.innerText = "edit";
editButton.className = "edit";
editButton.addEventListener("click", (e) => {
const btn = e.target;
const input = btn.parentElement.querySelector("input");
input.focus();
const previousVal = input.value;
input.addEventListener("keyup", (evt) => {
if (evt.keyCode === 13) {
if (input.value.trim() === "") {
input.value = previousVal;
}
input.disabled = true;
btn.disabled = false;
}
});
input.addEventListener("blur", () => {
input.disabled = true;
btn.disabled = false;
});
input.disabled = false;
btn.disabled = true;
});
return editButton;
}
const createRemoveBtn = () => {
const removeBtn = document.createElement("input");
removeBtn.setAttribute("type", "button");
removeBtn.setAttribute("value", "X");
removeBtn.addEventListener("click", (e) => {
e.target.parentElement.remove();
});
return removeBtn;
}
const createItem = () => {
const listItem = document.createElement("li");
listItem.innerHTML = `<input value="${input.value}" disabled=true>`;
display.appendChild(listItem);
input.value = "";
const editBtn = createEditBtn();
listItem.appendChild(editBtn);
listItem.appendChild(createRemoveBtn());
listItem.addEventListener("dblclick", (e) => {
displayDone.appendChild(listItem);
listItem.style.backgroundColor = "#54e346";
listItem.style.textDecoration = "line-through";
editBtn.style.display = "none";
});
}
const addAfterClick = () => {
if (input.value.length > 0) {
createItem();
} else {
alert("Write something mate!");
}
}
//List item can be added with "Enter" as well
const addWithEnter = (event) => {
if (event.keyCode === 13) {
addAfterClick();
}
}
// Remove all with user approve
const removeAll = (event) => {
const answer = prompt(`Type "Delete All" If you are that sure!`);
if (answer === "Delete All") {
display.innerHTML = "";
displayDone.innerHTML = "";
} else {
alert("Try One More Time");
}
}
//Event Listeners
button.addEventListener("click", addAfterClick);
input.addEventListener("keyup", addWithEnter);
deleteAll.addEventListener("click", removeAll);
<div class="main-container">
<h2 class="title">to do list <i class="fas fa-pencil-alt"></i></h2>
<div class="content">
<input id="inputText" type="text" placeholder="Add to your list..." maxlength="20" />
<i id="addButton" class="fas fa-plus">add Icon</i>
<div class="remove-container">
<i id="delete-icon" class="far fa-trash-alt">delete icon</i>
<p id="remove-text">Delete All</p>
</div>
<ul id="display"></ul>
</div>
<div class="completed">
<h2 class="title-done">
completed tasks <i class="far fa-check-circle"></i>
</h2>
<ul id="display-done"></ul>
</div>
</div>
I'm running into a problem. How can I console.log the selected option/value from the datalist when selecting/clicking with my mouse?
var input = document.querySelector("input");
var options = Array.from(document.querySelector("datalist").options).map(function(el){
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var relevantOptions = options.filter(function(option){
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if(relevantOptions.length > 0){
input.value = relevantOptions.shift(); //Taking the first
console.log(input.value)
}
}
});
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
If I understand correctly, select your element and add an eventListener to it that listens to 'change'
const input = document.querySelector('input');
input.addEventListener('change', (e) => { console.log(e.target.value) })
In your example just do this
var input = document.querySelector("input");
// above mentioned eventListener
input.addEventListener('change', function(event){
console.log(`selected value: ${event.target.value}`)
})
var options = Array.from(document.querySelector("datalist").options).map(function (el) {
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
var relevantOptions = options.filter(function (option) {
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if (relevantOptions.length > 0) {
input.value = relevantOptions.shift(); //Taking the first
console.log(input.value)
}
}
});
i have been trying to clear the text box after pressing the enter key, but i couldn't find any solution for this, been searching for over 2 hours.. this is the code:
html:
<!DOCTYPE html>
<html>
<body>
<style>
input{
margin-top:300px;
margin-left:580px;
}
ul{
margin-left:580px;
}
</style>
<input type="text" id="textBox" value = "" />
<ul id="dynamic-list"></ul>
<script src="script.js"></script>
</body>
</html>
javascript:
function addItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("textBox");
var li = document.createElement("li");
li.setAttribute('id',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
document.getElementById('candidate').value = "";
document.getElementById('textBox').value = "";
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
addItem();
}
});
There is no element whose ID is candidate in your HTML code. So JavaScript throws and error and stops executing the next statement. That's why the textbox doesn't clean up.
Remove the buggy statement, and your code works just fine:
function addItem() {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("textBox");
var li = document.createElement("li");
li.setAttribute('id', candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
document.getElementById('textBox').value = "";
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
addItem();
}
});
<input type="text" id="textBox" value="" />
<ul id="dynamic-list"></ul>
I am currently using an add button to add input from a text box into a list. I am also binding a button to each of these list elements and then appending them to the unordered list. How do I remove the element onclick of the corresponding remove button? Pure JavaScript only.
window.onload = function() {
var elements = [];
var textInput;
document.getElementById("addButton").onclick = function() {
textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
}
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<!DOCTYPE html>
<html>
<body>
<head>
<script src="func.js"></script>
</head>
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>
</body>
</html>
Use addEventListener to register click event over created button.
Use .remove(), removes the object from the tree it belongs to.
Try this:
window.onload = function() {
var elements = [];
document.getElementById("addButton").onclick = function() {
var textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
btnNode.addEventListener('click', removeHandler);
}
}
function removeHandler() {
this.parentNode.remove(); // this will be `button` element and `parentNode` will be `li` element
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>