this is the function I have written which will be executed when you click the button('create'). but somehow it is not creating the element.
It gets the value of the text written in the input tag using value attribute.
function create() {
let text1 = document.getElementById('input').value;
if (text1.trim() == "" || text1.trim() == null){
return false;
}
else{
document.getElementById("input").value = "";
}
let li = document.createElement('li');
li.setAttribute('class', 'todo');
document.getElementById('list').appendChild(li);
let p1 = document.createElement('p');
p1.setAttribute('class', 'text');
let teks = document.createTextNode(text1);
p1.appendChild(teks);
li.appendChild(p1);
let btn1 = document.createElement('button');
btn1.innerHTML = 'Edit';
btn1.setAttribute('class', 'buttons1');
btn1.setAttribute('onclick', 'edit()')
let btn2 = document.createElement('button');
btn2.innerHTML = 'Delete';
btn2.setAttribute('class', 'buttons2');
btn1.setAttribute('onclick', 'delete()')
li.appendChild(btn1);
li.appendChild(btn2);
}
I am building a small todo list and want to do the following: each text input (or actually a copy of the text input) should be added to an empty string (copy because it should not disappear when added). Then I have a function which is called when user clicks on a button and then I want to pick a random todo thing.
I didn't even get to the point when I pick out a random todo thing because my code just doesn't work- It seems like the adding does happen, but instead of adding a todo thing, thats being added:[object HTMLInputElement]
Anyone has an idea?
My javascript code:
var totalItems=0;
var listOf="";
function randomItem(){
document.getElementById("randomArray").innerHTML=listOf;
}
function updatingItem() {
var cbId = this.id.replace("cb_", "");
var textItem = document.getElementById("item_" + cbId);
if (this.checked) {
textItem.style.textDecoration = "line-through";
textItem.style.background="pink";
}
else {
textItem.style.textDecoration = "none";
textItem.style.background="white";
}
}
function addItem() {
totalItems++;
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "cb_" + totalItems;
checkBox.onclick = updatingItem;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.innerHtml = textItem;
var textItem = document.getElementById("textItem");
span.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
var listOfItems=textItem;
listOf+=listOfItems;
}
var item = document.getElementById("add");
item.onclick = addItem;
document.getElementById("lastButton").onclick=randomItem;
HTML:
<body>
<div class="table">
<h1>To Do List</h1>
</div>
<p>
<input type="text" id="textItem"/>
<button id="add"><b>Add</b></button>
</p>
<ul id="todoList"></ul>
<h3>Pick a random to do thing to do for today</h3>
<button id="lastButton">Go!</button>
<p id="randomArray"></p>
</body>
Your randomItem() function is working incorrectly, as you are trying to create String from Object directly while using listOfItems. Either use its value or try using following code instead for proper view. Also add one list element in HTML with id="myList". IT will work fine.
JS:
function randomItem(){
var counter = 0;
var textItems = document.getElementsByTagName("input");
var done = [];
for (var i=0; i<textItems.length; i++)
{
if(textItems[i].type == "checkbox")
{
if(textItems[i].checked)
{
document.getElementById("item_"+i);
done.push(document.getElementById("item_"+i).innerHTML);
var list = document.getElementById('myList');
var data = document.createElement('li');
data.appendChild(document.createTextNode(done[counter]));
counter++;
list.appendChild(data);
}
}
}
}
HTML:
<ol id = "myList"></ol>
try
var listOfItems=textItem.value;
rather than
var listOfItems=textItem;
Actually i am beginner in javascript and i am making a todo list with only javascript and given is my code..
function updateItemStage() {
var cbId = this.id.replace("cb_", "");
var itemText = document.getElementById("Item_" + cbId);
if (this.checked) {
itemText.className = "checked";
} else {
itemText.className = "";
}
}
function addNewItem(list, itemText) {
totalItems++;
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.onclick = updateItemStage;
checkBox.id = "cb_" + totalItems;
var span = document.createElement("span");
span.innerHTML = itemText;
span.id = "Item_" + totalItems;
listItem.appendChild(checkBox);
listItem.appendChild(span);
list.appendChild(listItem);
}
var totalItems = 0;
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
var todoInput = document.getElementById("todoInput")
var itemText = todoInput.value;
if(!itemText || itemText == "") {
return false;
}
addNewItem(document.getElementById("todolist"), itemText);
};
Using this code i successfully create a todo list but in this code i didn't get what is the main role and work of this keyword..
can anyone help me please to understand this problem ???????????
The this keyword is the element where your event happens
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.onclick = updateItemStage;
In your case, this is the checkBox which you clicked.
Im new to javascript and coding in general, I'm trying to make a simple to do list but cant get the delete button to delete all the checkboxes, it will only delete the first checkbox made. Thanks guys.
http://jsfiddle.net/fbct3oL7/1/
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
listItem.id = task;
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
checkbox.name = task;
checkbox.id = "checkbox";
document.getElementById('place').appendChild(listItem);
document.getElementById(task).insertBefore(checkbox, listItem.firstChild);
}
function deleteCheckBox() {
while (document.getElementById('checkbox').checked === true) {
var itemNode = document.getElementById(checkbox.name);
itemNode.parentNode.removeChild(itemNode);
}
}
I've modified your code, eliminating unnecessary id and name attributes, and updated the deleteCheckBox function to cycle through all the li in the ul.
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
listItem.appendChild(checkbox);
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
document.getElementById('place').appendChild(listItem);
}
function deleteCheckBox() {
var ul = document.getElementById('place');
var li = ul.children;
for (var i=0; i < li.length; i++) {
while(li[i] && li[i].children[0].checked) {
ul.removeChild(li[i]);
}
}
}
<div id="list">
<input type='text' id='textinput' />
<input type='button' onclick='taskadd()' value='Add to list' />
<input type='button' onclick="deleteCheckBox()" value='Delete' />
<ul id="place"></ul>
</div>
I also forked and updated your Fiddle: http://jsfiddle.net/JohnnyEstilles/gtpdLkLq/.
You give every checkbox the same id, and the getElementById method only returns the first matching element.
If you want to get all checkboxes and delete the checked ones you could start by doing like this. (Please notice that this code is written freehand and untested)
var inputs = document.getElementsByTagName("input");
for(i=o; i < inputs.length; i++){
if(inputs[i].type == "checkbox" && inputs[i].checked){
inputs[i].parentNode.removeChild(inputs[i]);
}
}
First get all element with the tag "input", then check if they are of checkbox type and checked.
So I'm trying to to basically dynamically create li's inside an array, and I would like to create a 'delete' button within each li, so that when I click that li, I can delete that specific li.
I know this seems very basic, but I've been looking at JS for hours now, and am starting to really confuse myself here.
I keep getting errors like addChild() is not a function... I feel like I'm close, but no cigar. Thanks in advance!
Anyway, here's my add function:
function add(){
var deleteBtn = document.createElement('input');
deleteBtn.type = 'submit';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
for(i=0;i<1;i++){
id_number[i] = i+1;
var newSong = '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
// $(newSong).appendChild(deleteBtn);
$(deleteBtn).appendTo("#playlist-1");
$(newSong).appendTo("#playlist-1");
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(newSong);
});
}
}
Here's my delete function
function deleteFromPlaylist(newSong){
var deleteBtn = document.getElementsByTagName('deleteButton');
// var deleteMe = deleteBtn.parentNode;
alert(deleteBtn);
for(i=0;i<showList.length;i++){
if(newSong === showList[i]){
showList.splice(i,1);
// var pp = p.parentNode;
// pp.removeChild (p);
deleteMe = deleteMe.parentNode.remove("li_test");
deleteMe.removeChild(deleteBtn);
}
// console.log(deleteMe);
}
}
EDIT: 1 More Related Question
I would like to only add an item if it doesn't exist already in the array. Here is what I have so far. Any tips on where I'm going wrong?
for (i = 0; i < showList.length; i++) {
if (newSong !== showList[i]){
ul_list.innerHTML = newSong;
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
alert("It IS in the Array!");
}else{
alert("This already exists!");
}
}
You seem to have a strange mix of code. Forget the jQuery stuff until you know javascript.
> function add(){
> var deleteBtn = document.createElement('input');
> deleteBtn.type = 'submit';
I don't think that's a good idea. Much better to use type button or a button element.
> deleteBtn.name = 'addButton';
> deleteBtn.className = 'deleteButton';
>
> for(i=0;i<1;i++){
Presumably i will go a bit higher in future. ;-)
> id_number[i] = i+1;
Where did id_number come from?
>
> var newSong = '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
> // $(newSong).appendChild(deleteBtn);
Stick to one method of creating elements. Consider using a document fragment to hold the parts.
> $(deleteBtn).appendTo("#playlist-1");
> $(newSong).appendTo("#playlist-1");
> showList.push(newSong);
Where did showList come from?
> deleteBtn.addEventListener('click', function(evt) {
> deleteFromPlaylist(newSong);
> });
Not all browsers support addEventListener. Since you are only adding one listener, consider just assigning to the button's onclick property. Note that newSong is just a string.
> }
> }
In the other function:
> function deleteFromPlaylist(newSong){
> var deleteBtn = document.getElementsByTagName('deleteButton');
There is no HTML "deleteButton" element, so that will return an empty collection.
> // var deleteMe = deleteBtn.parentNode;
> alert(deleteBtn);
> for(i=0;i<showList.length;i++){
> if(newSong === showList[i]){
> showList.splice(i,1);
> // var pp = p.parentNode;
>
> // pp.removeChild (p);
> deleteMe = deleteMe.parentNode.remove("li_test");
Where did deleteMe come from? You commented out where it was declared and it hasn't been assigned a value, so deleteMe.parentNode will throw an error.
> deleteMe.removeChild(deleteBtn);
> }
> // console.log(deleteMe);
> }
> }
> }
Anyhow, here's some working code, it's still pretty awful but I'll leave it to you go improve it.
<script>
var showList = [];
function add(){
var id_number = [];
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
deleteBtn.value = 'Delete Button';
for (i=0; i<1; i++) {
id_number[i] = i + 1;
// '<li class="li_test" id="' + id_number[i] + '">' + "<span>" + "</span>" + '</li>';
var newSong = document.createElement('li');
newSong.className = 'li_test';
newSong.id = id_number[i];
newSong.appendChild(document.createElement('span').appendChild(document.createTextNode('song')));
showList.push(newSong);
deleteBtn.onclick = (function(id) {
return function(){deleteFromPlaylist(id);}
}(newSong.id));
newSong.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(newSong);
}
}
function deleteFromPlaylist(id) {
var song = document.getElementById(id);
if (song) {
song.parentNode.removeChild(song);
}
}
window.onload = function() {
add();
}
</script>
<ul id="playlist-1">
<li>Original
</ul>
I've altered your code and functions to purely use javascript, instead of a mixture containg jquery. I've added comments in the code to explain my actions. If you have any questions, feel free to ask.
var showList = [];
var inc = 1;
function add() {
//create the container element. If we do this, keeping track of all elements
//becomes easier, since we just have to remove the container.
var container_div = document.createElement('div');
container_div.id = "cont_" + inc;
var ul_list = document.createElement('ul');
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.value = 'remove song';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
var id_number = [];
var newSong = "";
for (i = 0; i < 1; i++) {
id_number[i] = i + 1;
newSong += '<li class="li_test" id="cont_' + inc + '_song_id_' + id_number[i] + '">' + "<span>test " + inc + "</span>" + '</li>\n'; //all ids must be unique, so we construct it here
}
ul_list.innerHTML = newSong;
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(newSong);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
}
function deleteFromPlaylist(evt, newSong) {
var deleteBtn = evt.target; //target the button clicked, instead of a list of all buttons
var container_div = deleteBtn.parentNode; //get the parent div of the button
var cont_parent = container_div.parentNode; //and the parent of the container div
for (i = 0; i < showList.length; i++) {
if (newSong === showList[i]) {
showList.splice(i, 1);
}
}
cont_parent.removeChild(container_div); //finally, remove the container from the parent
}
Update:
I've modified the above function to strictly use objects, rather than strings, because it is easier to extract relevant information from objects, than strings.
I've added in comments to assist with understanding the code. Again, if you have any questions, feel free to ask.
function add() {
var list_bool;
//create the container element. If we do this, keeping track of all elements
//becomes easier, since we just have to remove the container.
var container_div = document.createElement('div');
container_div.id = "cont_" + inc;
var ul_list = document.createElement('ul');
var deleteBtn = document.createElement('input');
deleteBtn.type = 'button';
deleteBtn.value = 'remove song';
deleteBtn.name = 'addButton';
deleteBtn.className = 'deleteButton';
var list_item = document.createElement("li"); //create list element
list_item.className = "li_test"; //set element class
var list_span = document.createElement("span"); //create span element
list_span.innerHTML = "test"; //set span text
list_item.appendChild(list_span); //append span to list element
ul_list.appendChild(list_item); //append list element to un-ordered list element
var list_bool = false; //create local boolean variable
if (showList.length > 0) { // loop through showList if it isn't empty
for (var i = 0; i < showList.length; i++) {
if (showList[i].innerText !== list_item.innerText) {
list_bool = true; //if song exists(comparing text values, set bool to true
} else if (showList[i].innerText === list_item.innerText) {
list_bool = false; //else, set it to false
break; //break out of loop.. we don't want it becoming true again, now do we?
}
}
} else {
list_bool = true; //showList is empty, set to true
}
if (list_bool) { //if true, do action of appending to list
container_div.appendChild(ul_list); //append the info
container_div.appendChild(deleteBtn);
document.getElementById('playlist-1').appendChild(container_div); //finally add it to the playlist div
showList.push(list_item);
deleteBtn.addEventListener('click', function(evt) {
deleteFromPlaylist(evt, newSong);
});
inc++;
}
}
DEMO, notice that add() is executed twice, but because the song 'test' already exists, it only executes the end action once.