Dynamically added function is not working correctly JavaScript - 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"

Related

pass click event between two page by localStorage

I want to take a click event from 2nd page . 1st page have a link for 2nd page, there have a button when click the button it add a HTML row on 1st page. I am trying to use localStorage for passing data. My code don't work, take a look below:
1st Page.html
HTML
<div id="content">
</div>
JS
var output = document.getElementById('content');
addEvent(window, 'storage', function (event) {
if (event.key == 'StorageName') {
output.innerHTML = event.newValue;
}
});
2nd Page.html
HTML
<input id="data" type="button" value="+" onclick="addRow()">
JS
addEvent(dataInput, 'keyup', function () {
localStorage.setItem('StorageName', this.value);
});
var dataInput = dataInput = document.getElementById('data');
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
You haven't defined your addRow() function properly. A function's name is defined with the keyword function, not inside of the function body. Your code:
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
Should be changed to:
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
object.onclick = addRow;
I agree with skyline3000's answer the addRow() should be defined. Also there are a few other things that could/should change:
define dataInput before attaching an event to it
object.onclick should be dataInput.onclick since thats the element being clicked. (is click event what you really want? maybe onkeyup?)
when you set the localStorage you want to set the function definition being passed to Page 1 which appears to be addRow(). Simply remove the parenthesis to pass just the definition.(Should also be defined before using)
If you want to just pass the function you shouldn't set the onclick event on Page 2. What you should probably do is record how many times you want it to run when you go to Page 1.
You dont need to pass the function everytime if it isnt changing; Just set it once and record the number of times it was clicked.
page 1 can catch the load event and the check localStorage for the function definition and number of times it was run. Then it can loop and perform the function.
the code you have doesn't add a link back to page 2 if thats what you are looking for but you can add that into the addrow function when you know the file name and path.
Page 1
var output = document.getElementById('content');
addEvent(window, 'load', function (event) {
if (localStorage.getItem('StorageName') && localStorage.getItem('rowsToAdd')) {
for(var i = 0; i > rowsToAdd;i++){
var addNewRow = localStorage.getItem('StorageName');
addNewRow();
}
}
});
Page 2
var dataInput = document.getElementById('data');
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
};
localStorage.setItem('StorageName', addRow);
dataInput.onclick = function() {
if(localStorage.getItem('rowsToAdd')){
localStorage.setItem('rowsToAdd', localStorage.getItem('rowsToAdd') + 1);
}else{
localStorage.setItem('rowsToAdd',1);
}
}
I didn't test this code so it may not work copy+pasted but something pretty close hopefully.
I also answered this with the best understanding of what you wanted that I could manage but I dont fully see the desired result of what you seemed to be doing.

Adding a function to button's onclick that has parameters

I'm having an issue trying to setup a row where by when the remove button is pressed, the row is removed from the table. When I set the onclick method as shown below, it will automatically remove the row upon creation of it. I assume it's calling the function
I've seen that you should remove the parenthesis when assigning such and that's causing the issue. But for obvious reasons I require the rows id to be able to remove the row.
name = "thomas";
foo = "foo";
bar = "bar";
// Create a new row
var row = table.insertRow();
row.id = name;
// Create cells with requested information
row.insertCell().innerText = name;
row.insertCell().innerText = foo;
row.insertCell().innerText = bar;
var removeButton = document.createElement("BUTTON");
removeButton.innerHTML = "Remove";
removeButton.onclick = deleteRow(row.id);
var removeButtonCol = row.insertCell();
removeButtonCol.appendChild(removeButton);
function deleteRow(rowID)
{
var row = document.getElementById(rowID);
row.parentNode.removeChild(row);
}
So how can I resolve this? I don't know how to setup an onclick for a function that requires parenthesis or an eaiser way to pass the row id when a button is pressed that belongs to a rwo
So it turns out I should be using an event listener instead of the onclick method.
EG, where we did onclick:
var removeButton = document.createElement("BUTTON");
removeButton.innerHTML = "Remove";
removeButton.addEventListener('click', function () {
deleteRow(row.id)
});
This works perfectly

onclick() automatic firing on loading but failing afterwards

I understand that onclick() in html with parenthesis calls automatically. But in my situation, I want to pass a parameter into the onclick function(specifically, the element clicked). So how do I manage this without having onclick fired when the page loads? In addition, the onclick method does not fire after its automatically firing upon loading. My code is below:
for (i = 0; i < returnPostPhotoSrcs().length; i++) {
// var photosArray=returnPhotoNames()
// var imgName=photosArray[i]
var imgSrcArray=returnPostPhotoSrcs();
var imgSrc=imgSrcArray[i]
var postNamesArray=returnPostNamesArray();
var postName=returnPostNamesArray[i]
var img=img_create(imgSrc,postName,'')
img.style.width=returnPostHeight();
img.style.height=returnPostWidth();
img.className="postImage";
img.onmousedown=playShout(img);
var postNamesArray=returnPostNames();
var innerSpan = document.createElement('span');
innerSpan.onmousedown=playShout(innerSpan); //problem line
var text = postNamesArray[i];
innerSpan.innerHTML = text; // clear existing, dont actually know what this does
var outerSpan = document.createElement('span');
outerSpan.className="text-content";
outerSpan.onmousedown=playShout(outerSpan); //another problem line, also doesnt call onclick
var li = document.createElement('li');
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(img)
outerSpan.appendChild(innerSpan)
li.appendChild(imgSpacer)
imgSpacer.style.opacity="0"
// if (i>0 && i<returnPostPhotoSrcs().length-1) {
// hackey
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(imgSpacer)
li.appendChild(outerSpan)
imgSpacer.style.opacity="0"
// }
var outerDiv = document.getElementById("postDivOuter");
outerDiv.appendChild(li)
}
Adding onto this you could also do:
img.onmousedown= function(e) { playShout(e) };
//for playshout
playshout = function(e) {
var element = e.target; //this contains the element that was clicked
};
The function fires because you are calling it. You need to use a closure
img.onmousedown= function() { playShout(img) };
As others have shown, you can create an anonymous function, or another option is to use .bind():
innerSpan.onmousedown = playShout.bind(null, innerSpan);

dynamically add table row having buttons with onclick event

i want to add button in table row with onclick fuction. for that i am using
var cell9 = row.insertCell(8);
var edit = document.createElement("input"); // Create a <button> element
edit.id = "edit"+saveCount;
edit.type = "Button";
edit.value = "Edit Employee";
edit.name = "edit";// Create a text node
edit.onclick = editrow(id);
cell9.appendChild(edit);
in this code how to call function(with parameter as its id) on edit.onclick
edit.onclick
Wait for a function in order to execute it when the event occurs.
editrow(id);
Is not a function but the result of the function.
edit.onclick = function(){
editrow(id);
};
Will works better!

Trying to make a to do list

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.

Categories

Resources