Adding a function to button's onclick that has parameters - javascript

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

Related

How to set a css property to an html element that i get as a string

I generate an html table using javascript and jquery.
One of the row cells has an anchor element, that I append to table as a string var deleteLink = "Delete"
I need to set an event listener to the generated element, but don't know how to select it
I can't pass deleteLink as a string like this
$(deleteLink).on("click", function () {
//call fucntion
});
I'm trying to set a unique id to the generated links, but I also need to know how to select them first. Please help
This's how I generate the html table.
Please note that each delete link should only trigger the row it belongs to.
function appendToDigitalMapTable(docId) {
tbl = document.getElementById('digitalMapTable');
var selectedDigitalMap = $("#DigitalMapTypeId option:selected").text();
var deleteButton = "<a href='#'>Delete</a>";
addRow(tbl, selectedDigitalMap, deleteButton, docId);
}
function deleteUploadedDoc(docIdAssociatedToRow) {
console.log("deleteUploadedDoc function is called. docId = " + docIdAssociatedToRow);
//ajax call to backend function
}
function addCell(tr, val) {
var td = document.createElement('td');
td.innerHTML = val;
tr.appendChild(td)
}
function addRow(tbl, val_1, val_2, docId) { 2
var tr = document.createElement('tr');
var docIdAssociatedToRow = $(tr).data("documentID", docId)
//selected digitalMapType text
addCell(tr, val_1);
//delete row
addCell(tr, val_2);
//val_3 is "<a href='#'>Delete</a>"
//attach eventListener to this element
$(val_3).on("click", function () {
deleteUploadedDoc(docIdAssociatedToRow);
});
tbl.appendChild(tr)
}
Option 1: return the row from addRow then find the delete button in that row to add the event handler:
function addRow(...) {
...
return tr;
}
var tr = addRow(...);
var delbutton = $(tr).find("a")
// not clear if you question is for css or event handler, asks both
delbutton.css("color", "red").click(function() { handleRowDeleteEvent(); });
this assumes you only have one button/anchor, mitigated using a class
var delbutton = $(tr).find("a.del-button")
(as an aside, it should be a <button type='button' not <a> as it's an action, not a link, so I've used <button> below)
Option 2: use event delegation
$("#digitalMapTable").on("click", "a", handleRowDeleteEvent);
again, assumes you have a single button for delete, not for edit etc, but this can easily be mitigated by adding a class to your buttons when you create them, eg:
var deleteLink = "<button type='button' class='delete-button'>delete</button>";
$("#digitalMapTable").on("click", "button.delete-button", handleRowDeleteEvent);
Option 3: use onclick=
var deleteLink = "<button type='button' onclick='handleRowDeleteEvent'>delete</button>";
not recommended for numerous reasons that I'll leave you to research
How to ensure your button only works on the row it needs to - use this:
function handleRowDeleteEvent() {
var btn = $(this);
var row = btn.closest("tr");
var docId = row.data("documentID");
deleteUploadedDoc(docId);
}
or, all in one line:
function handleRowDeleteEvent() {
deleteUploadedDoc($(this).closest("tr").data("documentID"));
}
You can give your anchor element an unique id and later use Jquery's # selector to select that particular element.
var counter = 1;
var deleteLink
for (var a = 0; a < 2; a++) {
deleteLink = "<a href='#' id='myLink" + counter + "'>Delete </a>";
document.body.innerHTML += deleteLink;
counter++;
}
$('#myLink1').on("click", function() {
console.log("clicked")
});
$('#myLink2').on("click", function() {
console.log("other clicked")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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"

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.

How to set a javascript function to an element with no postback

I created an input type=file and I need to connect it to my Javascript function, the problem is that I get postback (I don't need server-side), I tried different ways (code below).. maybe I set the function wrong... Help please
++ createMyButton is fired from another function and works fine.
//JAVASCRIPT
function createMyButton(){
var deleteBtn = document.createElement('input');
deleteBtn.type = "button";
deleteBtn.title = "Delete";
//1 try
deleteBtn.onclick = 'deleteItem()';
//2 try
deleteBtn.onclick = 'deleteItem();return false';
}
//FUNCTION
function deleteItem() {
alert("delete");
}
These are the issue I seen
1.deleteBtn.onclick = 'deleteItem();' are you missing quote "''here ?
2
. If u want to bind event to element use addEventListener to for
E.g
var deleteBtn = document.createElement('input');
deleteBtn.type = "button";
deleteBtn.title = "Delete";
// you missed button value here
deleteBtn.value = "Delete";
deleteBtn.addEventListener('click', deleteItem);
//FUNCTION
function deleteItem() {
var btn = this; // you can use button here
alert("delete");
}
JSBIN EXAMPLE

Categories

Resources