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>
Related
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("");
}
}
});
});
From the code in my previous question, i now have a function "knapsack" that is supposed to disable the buttons when the total weight(tot_weight) is greater than or equal to the maximum weight("max_weight"). I need it to disable all the "add" buttons when the condition is met.(this will cause no more input to be accepted when max capacity is reached)
My code does not work correctly, it justs disable the last button after only selecting one item (i dont think it checks the condition).
arr_items = new Array();
knap = new Array();
let input = document.getElementById("userinput");
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
let ul = document.getElementById("list");
let ul2 = document.getElementById("knap")
let listCount = 0;
let myfunction2;
let knapsack;
let max_weight;
myfunction2 = () =>{
input.value = "";
}
let inputLength=() => input2.value.length;
let addValues = () =>{
inputs = {
name : input2.value,
weight : parseFloat(input3.value),
value : parseInt(input4.value)
}
arr_items.push(inputs);
console.log(arr_items);
createListElement();
myfunction2();
}
let createListElement = () => {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input2.value));
ul.appendChild(li);
input2.value = "";
input3.value = "";
input4.value = "";
let btn = document.createElement("button");
btn.appendChild(document.createTextNode("Add"));
li.appendChild(btn);
btn.className = "butt";
btn.id = listCount;
btn.onclick = addTo;
listCount++; // increment the list count variable
console.log(input.value);
max_weight = input.value;
knapsack = (max_weight,knap)=>{
let tot_weight = 0;
for(i=0; i<knap.length;i++){
tot_weight = knap[i].weight + tot_weight;
}
console.log(tot_weight);
console.log(max_weight);
if (tot_weight >= max_weight){
btn.disabled = true;
}
}
}
function addTo(){
var li2 = document.createElement("li");
var id = parseInt(this.id); // retrieve the id of the button
li2.appendChild(document.createTextNode(arr_items[id].name));
ul2.appendChild(li2);
knap.push(arr_items[id]); //use the id of the button to select array to push to knap from the array item
console.log(knap);
knapsack(max_weight,knap);
}
let addListAfterClick = () =>{
if (inputLength() > 0) {
addValues();
}
}
<!DOCTYPE html>
<html>
<head>
<title>KnapSack</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>KnapSack</h1>
<div>
<input id="userinput" type="number" placeholder="Enter Capacity">
</div><br>
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
<button onclick="addListAfterClick()" id="value">Enter</button>
</div>
<ul id="list">LIST OF 20 ITEMS TO CHOOSE FROM
</ul>
<ul id="knap"> LIST OF ITEMS IN KNAPSACK
</ul>
<div>
<button onclick="myFunction()" id="done">Done</button>
</div>
<p id="demo"></p>
<script type="text/javascript" src="script.js"></script>
<script src="jquery-3.2.1.min.js" ></script>
</body>
</html>
From your code max_weight is being reset every time the "Add" button is clicked, this might make the condition to disable the "Add" buttons behave abnormally.
To disable all the buttons, you have to get all the buttons you created with the ClassName you assigned to them. Here is the modification of your code
arr_items = new Array();
knap = new Array();
let input = document.getElementById("userinput");
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
let ul = document.getElementById("list");
let ul2 = document.getElementById("knap")
let listCount = 0;
let myfunction2;
let knapsack;
let max_weight;
let tot_weight = 0;
myfunction2 = () =>{
//input.value = ""; I had to comment this line out to avoid resetting max_weight value everytime the add button is click
// since we need to evaluate it everytime
}
let inputLength=() => input2.value.length;
let addValues = () =>{
inputs = {
name : input2.value,
weight : parseFloat(input3.value),
value : parseInt(input4.value)
}
arr_items.push(inputs);
console.log(arr_items);
createListElement();
myfunction2();
}
let createListElement = () => {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input2.value));
ul.appendChild(li);
input2.value = "";
input3.value = "";
input4.value = "";
let btn = document.createElement("button");
btn.appendChild(document.createTextNode("Add"));
li.appendChild(btn);
btn.className = "butt";
btn.id = listCount;
btn.onclick = addTo;
listCount++; // increment the list count variable
console.log(input.value);
max_weight = input.value;
knapsack = (max_weight,knap)=>{
for(i=0; i<knap.length;i++){
tot_weight = knap[i].weight + tot_weight;
}
console.log(tot_weight);
console.log(max_weight);
if (tot_weight >= max_weight){
let buttons = document.getElementsByClassName("butt"); // get all the buttons
for( let button of buttons){
button.disabled = true; // disable all the buttons
}
}
}
}
function addTo(){
var li2 = document.createElement("li");
var id = parseInt(this.id); // retrieve the id of the button
li2.appendChild(document.createTextNode(arr_items[id].name));
ul2.appendChild(li2);
knap.push(arr_items[id]); //use the id of the button to select array to push to knap from the array item
console.log(knap);
knapsack(max_weight,knap);
}
let addListAfterClick = () =>{
if (inputLength() > 0) {
addValues();
}
}
<!DOCTYPE html>
<html>
<head>
<title>KnapSack</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>KnapSack</h1>
<div>
<input id="userinput" type="number" placeholder="Enter Capacity">
</div><br>
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
<button onclick="addListAfterClick()" id="value">Enter</button>
</div>
<ul id="list">LIST OF 20 ITEMS TO CHOOSE FROM
</ul>
<ul id="knap"> LIST OF ITEMS IN KNAPSACK
</ul>
<div>
<button onclick="myFunction()" id="done">Done</button>
</div>
<p id="demo"></p>
<script type="text/javascript" src="script.js"></script>
<script src="jquery-3.2.1.min.js" ></script>
</body>
</html>
I think this should work as expected
The issue is that in createListElement() you are only disabling the button you just created:
let btn = document.createElement("button");
...
if (tot_weight >= max_weight){
btn.disabled = true;
}
What you want is for all buttons to be disabled, so you could do something like getting all buttons by className, and disabling them in a loop:
allButtons = document.getElementsByClassName( "butt" );
if (tot_weight >= max_weight){
for ( const button of allButtons ) {
button.disabled = true;
}
}
The conditional is definitely being checked every time. This should fix it.
Entered todo is shown but the date is not being shown. Am i using any wrong command?? On entering a data, date should be shown on the left of the todo, just below the input area.
var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');
function store(ele) {
if (event.keyCode == 13) {
changeText();
}
}
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
changeDate();
}
}
function changeDate() {
var d = new Date();
var dates = document.createElement("div");
dates.className = "myClass";
dates.innerHTML = document.createTextNode(d.toDateString());
list2.innerHTML = dates;
}
<div class="container">
<h1>
Your todos
</h1>
<input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
<div class="todos">
<ul id="demo"></ul>
</div>
</div>
First of all your JS has an issue. The list2 is a HTMLCollection and there's no .innerHTML for that. You need to use:
list2[0].innerHTML
You don't even need that. The date issue is because of the Date Object incorrectly being set / inserted.
var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');
function store(ele) {
if (event.keyCode == 13) {
changeText();
}
}
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
changeDate(list);
}
}
function changeDate(which) {
var d = new Date();
which.innerHTML += d.toDateString();
}
<div class="container">
<h1>
Your todos
</h1>
<input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
<div class="todos">
<ul id="demo"></ul>
</div>
</div>
Preview
instead of this:
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
changeDate(list);
}
}
try this:
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
changeDate(list); //call this before appending data
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
}
}
and CSS:
li{
display: inline-block;
}
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>
function newCheckbox(){
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElementById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num){
var elm = null;
try {
elm=document.createElement('<input type="checkbox" id="chk'+num+'">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.id='chk'+num;
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
for(var i = 0; i<texts.length-1; i++){
var chbox=Box[i];
txt = texts[i];
if(chbox.checked){
chbox.parentNode.removeChild(chbox);
txt.parentNode.removeChild(txt);
}
}
}
form{
color:blue;
font-weight:bold;
margin:100 0 0 50;
font-weight:bold;
margin-left:120;
padding:100;
}
label{
display:block;
}
input{
color:blue;
background-color:pink;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" name="form1">
<div>
<label>Checkbox text:<input type="text" id="text"></label>
<input type="button" onclick="newCheckbox();"value="add">
<input type="button" value="Delete" onclick = "delBoxes();"/>
</div>
</form>
</body>
</html>
I want to have a dynamic page that allows a user to add checkboxes to the page. Checkbox content is the input in the textbox.
When the user pushes the “add”-button checkboxes are created and shown. The user must have the ability to remove checkboxes by marking them. The code can add a new checkbox to the form but the deleting function does not work.
It seems that chbox is not created and the if-statement does nothing in the function delBoxes.
Any suggestions?
Replace the whole script you have with this :
function newCheckbox() {
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElementById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num) {
var elm = null;
try {
elm=document.createElement('<input type="checkbox" class="chk">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.className='chk';
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
var chbox = document.form1.getElementsByClassName('chk');
for(var i = 0; i<texts.length-1; i++){
if(chbox[i].checked){
chbox[i].parentNode.removeChild(chbox[i]);
texts[i].parentNode.removeChild(texts[i]);
}
}
}