Trying to make a to do list - javascript

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 last checkbox made. Thanks guys
http://jsfiddle.net/2L8y73ac/
var task = document.getElementById('textinput');
function ObjectTask() {
self = this;
self.init = function() {
self.itemText=document.createTextNode(task.value);
self.checkbox = document.createElement("input");
self.checkbox.type = "checkbox";
self.checkbox.name = task.value;
self.checkbox.id = "checkbox";
self.checkbox.value = "0";
self.checkbox.onclick = self.clickMe;
self.listItem=document.createElement("li");
self.listItem.id = task.value;
self.listItem.appendChild(self.itemText);
self.listItem.appendChild(self.checkbox);
self.deleteCheckBox = document.getElementById('deleteBtn');
self.deleteCheckBox.onclick = self.deleteMe;
document.getElementById('place').appendChild(self.listItem);
}
self.clickMe = function() {
if (self.checkbox.value === "0") {
self.checkbox.value = "1";
console.log("1");
}else {
self.checkbox.value = "0";
console.log("0");
}
}
self.deleteMe = function(){
if (self.checkbox.value == "1"){
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
}
function taskadd() {
var taskNew = new ObjectTask();
taskNew.init();
}

I can't seem to get the adding to work either, but that doesn't matter. :)
The problem is that you assign a new click handler to the single delete button everytime when you add an item. When you click the delete button, the event handler of the last item is called, everytime (even when the item itself is already deleted).
The problem is in this piece of code:
self.deleteCheckBox = document.getElementById('deleteBtn');
self.deleteCheckBox.onclick = self.deleteMe;
deleteCheckBox is assigned the (global) delete button. After that, you assign a new onclick handler to it, overwriting the previous one.
A better approach would be to write one generic handler for the delete button, which looks up all selected checkboxes and finds the other elements belonging to it to delete them. So just like your global taskadd(), you should also have a global taskdelete() that deletes all selected tasks.

Related

I cant seem to fetch the localstorage string. it shows up in the " localstorage tab " but i just cant retrieve the data, after refresh

`use strict`;
//assigned all btns to a variable
const addbtn = document.querySelector('.addbtn');
const deletebtn = document.querySelector('.deletebtn');
const clearbtn = document.querySelector('.clearbtn');
const saveList = document.querySelector(`.save`);
var addList = document.createElement('LI');
let listCount = [];
//LOCAL STORAGE
JSON.parse(localStorage.getItem(`saved`));
// alert(localStorage.getItem(`saved`));
localStorage.getItem(`saved`);
//FUNCTIONS
//SAVE
saveList.addEventListener(`click`, function() {
localStorage.setItem('saved', JSON.stringify(listCount));
alert(localStorage.getItem(`saved`));
location.reload();
});
//DELETEALL BUTTON
const deleteAll = function() {
var ulList = document.getElementById('list');
var deleteList = document.getElementsByTagName('li');
while (deleteList.length > 0) {
console.log(ulList.removeChild(deleteList[0]));
}
};
//EVENTLISTENER
clearbtn.addEventListener('click', deleteAll);
// /// ADDING FUNCTION
addbtn.addEventListener('click', function() {
const textBoxValue = document.querySelector('.text-box');
let value = textBoxValue.value;
if (value === '') {
alert(`Please add a chore`);
} else {
var ulList = document.getElementById('list');
var addList = document.createElement('LI');
addList.textContent = value;
listCount.push(value);
addList.className = 'list-text';
ulList.appendChild(addList);
textBoxValue.value = '';
//create delete button on list//
var deleteSingle = document.createElement('button');
deleteSingle.setAttribute('class', 'btn button');
//delete clicked list//
deleteSingle.appendChild(document.createTextNode('Delete'));
addList.appendChild(deleteSingle).addEventListener('click', function() {
this.parentNode.remove();
});
}
});
im new here so im slowly learning how to properly post questions on here. sorry for the sloppiness.
i have spent my last 4 hours trying to find the easiest way to just save my todo list so when page is refresh my todos are still there. i tried adding it on the addbtn function but i couldnt get it to work. i thought adding it there so once the add buttong is clicked automatically would save it to the local storage, but i didnt manage to make that work. so then i created an empty global array and when the addbtn is clicked the input gets added to the array and made a "save" button to save the array into the localstorage and then retrieve it once the page is refresh but i cant get it to work. i see my array list in the localstorage tab but when i refresh the page the list on the actual page is empty. what am i missing? and what do you think is the easiest way to add this into my code?
once again sorry for messy code and thank you soo much in advance.

Dynamically added function is not working correctly JavaScript

I'm trying to create a table made out of user inputs, with those inputs including checkboxes.
I have a function for what to do when the box is clicked
function checkTheBox(t) {
var t;
if (array[t] == 0) {
array[t] = 1;
}
else {
array[t] = 0;
}
}
and to add that function to the created elements of the table I use
function add() {
var word = document.getElementById("text").value;
var tdt = document.createElement("td");
var tdc = document.createElement("td")
var node = document.createTextNode(word);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "cb";
tdc.addEventListener("click", ticker(0), false);
tdc.stopPropagation;
tdt.appendChild(node);
tdc.appendChild(checkbox);
var tr = document.createElement("tr");
tr.appendChild(tdt);
tr.appendChild(tdc);
var table = document.getElementById("vt");
table.appendChild(tr);
}
The problem is that whenever I click on the Add button to create the new element it activates the function and then creates the element and the checkbox does nothing when I click on it.
I use the checkTheBox function in the first place because the only other way I've read of dealing with checkboxes is with PHP, which I have yet to delve into.
You're executing ticker(0) immediately, rather than telling it to execute when tdc is clicked.
Here...
tdc.addEventListener("click", ticker(0), false);
That will assign the result of executing ticker(0) to the click event handler. You can wrap it in an anonymous function so that it is only executed later...
tdc.addEventListener("click", function() { ticker(0); }, false);
Have a look at the documentation here for some examples...
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Search that page for "anonymous function"

JavaScript conditions for checkbox OnLoad

I have a checkbox which determines whether to hide or make elements visible. My question: is there a way to also include if the checkbox was originally unchecked on page-load to permanently remove those elements so they can't be recalled, otherwise continue what is currently below? Hope that makes sense.
function myEmail() {
var emailBox = document.getElementById("checkemail");
var emailradios = document.getElementById("emailradios");
var emailOptOutSix = document.getElementById("emailOptOutSix");
var emailOptOutForever = document.getElementById("emailOptOutForever");
if (emailBox.checked == true){
emailradios.style.visibility = "hidden";
emailforever.style.visibility = "hidden";
emailOptOutSix.checked = false;
emailOptOutForever.checked = false;
} else {
emailradios.style.visibility = "visible";
emailforever.style.visibility = "visible";
}
}
Its a little unclear what your asking. If you want to delete the items when the checkbox is unchecked (on page load) then you could do this:
Here is a working version JSFiddle
It should be noted, that getting the cookie using substring is not the best practice. It would be wise to create a function that handles this. An example can be found here. Working with cookies
//gets the cookie for checked/not checked state
var checked = document.cookie;
//On window load
window.onload = function() {
//Get the value of the cookie
var emailBoxChecked = checked.substring(checked.indexOf("=") + 1);
if (emailBoxChecked == "checked"){
//set the state of the checkbox to true
document.getElementById("emailbox").checked = true
//If checked do something
} else {
//set the state of the checkbox to false
document.getElementById("emailbox").checked = false
//remove radio buttons that are contained within the emailRadios div
var parent = document.getElementById("myForm")
var child = document.getElementById("emailRadios")
parent.removeChild(child)
}
};
//Call this function when the checkbox is clicked
var emailChecked = function () {
var emailBoxChecked = document.getElementById("emailbox").checked
if (emailBoxChecked){
// store the state of the checkbox as checked in a cookie
document.cookie = "email=checked";
} else {
// store the state of the checkbox as NOT checked in a cookie
document.cookie = "email=unchecked";
}
}

How to assign event handlers to multiple elements (colorPicker)

I'm trying to find a way to assign event handlers to each box that I create dynamically. At the moment the user can click "Add above" or "Add below" and 2 rows of boxes will appear wherever they clicked.
I'm trying to make it so that when the user clicks on a specific square, a colorPicker will pop up and that specific square's color can be changed.
However, my program is a bit buggy, it only works for the first square that the user clicks on and the colorPicker never pops up again.
Does anyone know how I can go about fixing this or if there is a better alternative?
My code:
http://codepen.io/anon/pen/bwBRmw
var theParent = document.querySelector(".container");
theParent.addEventListener("click", doSomething, false)
//var picker = new Picker()
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
var picker = new Picker(k)
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}
I noticed in your CodePen that you didn't post the full code for doSomething. You have a problem because the picker variable is local to the function. If the code execution doesn't land inside the IF-statement, the picker variable is never created. Simply uncomment the code declaring the picker variable outside the function, and remove the var directive from in front of the line of code where you instantiate a new picker. Furthermore, you need to reset the "parent" element of the picker, since there is only one picker on the page: picker.settings.parent = k;
var picker = null; // Initialize global variable
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
// Reference the global "picker" variable
if (!picker) {
picker = new Picker(k)
} else {
// Set the "parent" element of the picker to the newly clicked element
picker.settings.parent = k;
}
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}

How to trigger an event after clicking two different button in Javascript

I was wondering how I can trigger an event after two different buttons being clicked. Specifically I have some buttons with different ids and I want when I click two specific buttons from them to trigger an event. I thought that this can be happen If I call some function in the first on click event and inside this function I can call another function if the second button being clicked. It does not seem to work, so I need your help. (If anyone needs more code please comment to upload the whole code)
function someKindOfFunction(){
//there is some other code here
var ob = document.getElementById(idTable[0]);
var ob1 = document.getElementById(idTable[1]);
var ob2 = document.getElementById(idTable[2]);
var ob3 = document.getElementById(idTable[3]);
ob.addEventListener("click",function() {onCl1(idTable[0],idTable)});
ob1.addEventListener("click",function() {onCl1(idTable[1],idTable)});
ob2.addEventListener("click",function() {onCl1(idTable[2],idTable)});
ob3.addEventListener("click",function() {onCl1(idTable[3],idTable)});
}
function onCl1(id1,idTable){
var obj1 = document.getElementById(id1);
obj1.disabled=true;
var obj2,v,obj3,obj4;
v=0;
var temp = ["0","0","0"];
for(var i =0 ; i<4 ; i++){
if( id1 != idTable[i]){
temp[v] = idTable[i];
v=v+1;
}
}
ob=document.getElementById(temp[0]);
ob1=document.getElementById(temp[1]);
ob2=document.getElementById(temp[2]);
ob.addEventListener("click",function() {onCl2(id1,temp[0])});
ob1.addEventListener("click",function() {onCl2(id1,temp[1])});
ob2.addEventListener("click",function() {onCl2(id1,temp[2])});
}
function onCl2(id1,id2){
//some kind of actions
alert("it wokrs");
}
Just pass some sort of value whenever the button you want is clicked. For instance:
ob.addEventListener("click",function() {onCl1(1)});
ob1.addEventListener("click",function() {onCl1(1)});
var i;
function onCl1(value){
i += value;
if(i == 2){
//do this
}
}
So basically once these two buttons are clicked the value will equal 2 and trigger whatever you want.

Categories

Resources