link a checkbox to an object in Javascript - javascript

Suppose I have a table which is populated by filling out a form on a page and clicking the submit button.
The last column of the table is a Completed section with a checkbox on each row. On clicking on the checkbox I want to change the .completed property from false to true on that object.
How can I distinguish which checkbox was clicked and change the property from that row?
this.addRowToTable = function() {
return "<tr id='tableRow'><td>" + this.app + "</td><td>" + this.priority + "</td><td>" + this.date + "</td><td>" + this.additionalNotes + "</td><td>" + "<input type='checkbox' class='checkApp[]' value='" + this.completed + "' />" + "</td></tr>";
};
I have all the checkboxes in the checkApp array, but Im not sure where to go from there?.
This is called when the form is submitted:
function addAppointment() {
if (txtApp.value == "" || txtPriority.value == "" || txtDate.value == "" || {
alert("Please fill all text fields");
} else {
var app = new Appointment(txtApp.value, txtPriority.value, txtDate.value, txtNotes.value, false);
apps.push(app);
localStorage.setItem("apps", JSON.stringify(apps));
clearUI();
}
updateTable();
updateTable() loops through all objects in my array and adds them between table tags:
for (var i = 0; i < apps.length; i++) {
var app = new Appointment(apps[i].app, apps[i].priority, expenses[i].date, apps[i].notes, false);
tblHTML += app.addRowToTable();
}
My Appointment Object:
function Appointment(app, priority, date, notes, completed) {
this.app = app;
this.priority = priority;
this.date = date;
this.additionalNotes = notes;
this.completed = completed;
this.addRowToTable = function { ... };
}

First of all, in HTML, id attributes should be unique. So, make sure table rows have unique IDs. At the moment, all of them have the identical ID of tableRow.
Besides, you should consider using a framework/library such as jQuery for real-world scenarios rather than creating the DOM elements, etc. manually.
Now back to the original problem: if you use the DOM API rather than string concatenation to create the table rows, you can add custom fields to the DOM objects representing the table rows. So, from each table row, you can have a reference back to its corresponding Appointment object:
var row = document.createElement("tr");
row.appointment = this;
Similarly, you can use the DOM API to create the table cells as well as the checkbox:
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
where addTd is the following function:
function addTd(row, innerHTML) {
var td = document.createElement("td");
td.innerHTML = innerHTML;
row.appendChild(td);
}
Now that you are using the DOM APIs, you can easily attach event listeners to each checkbox object as well.
Then inside the event listener you can get a reference back to the Appointment corresponding to the row you
have changed its checkbox:
var row = document.createElement("tr");
row.appointment = this;
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
input.addEventListener("change", function(event) {
var row = this.parentNode.parentNode,
appointment = row.appointment;
// change appointment however you like
});

Related

How to append html to table td?

I am looping through a grids datasource and when it gets to ToFactory not being empty I need to add a div into its td cell. Below is the code that I am using to get the td at index 18 of its row
var data = this.dataSource.view();
for(i=0;i<data.length;i++){
var dataItem = data[i];
var tr = $("#QuickEntryGrid").find("[data-uid='" + dataItem.uid + "']");
if(dataItem.ToFactory != ""){
let me = tr.find('td')[18];
me.innerHtml = "<div class='abc'>1234</div>"; // Doesn't work
console.log(me);
}
}
the variable me is
<td class role='gridcell'></td>
and what I would like to put in the td is
<div class='abc'>123</div>
and me should look like this
<td class role='gridcell'><div class='abc'>123</div></td>
but its not happening,
any idea's on why I am not getting this working? I have also tried
me.append("<div class='abc'>123</div>");

Buttons disapper on adding new list items?

I am creating a list using javascript.After every list item, there are two buttons inserted. But these buttons appear only on last list item.Please help me.
My Code
Here is my function which updates the list using JS`
function updateView() {
fetchFromLocal(); //fetches list from local storage and updates TaskList array
list.innerHTML = ""; //list is var that points to unordered list
var checkbox = document.createElement("input");
checkbox.setAttribute('type', 'checkbox');
var btnUp = document.createElement("input");
btnUp.setAttribute('type', 'button');
btnUp.setAttribute('value', '^');
// console.log(btnUp);
var btnDown = document.createElement("input");
btnDown.setAttribute('type', 'button');
btnDown.setAttribute('value', 'v');
for(var i=0;i<TaskList.length;i++)
{
var TempElem = document.createElement("li");
//console.log(TempElem);
TempElem.appendChild(checkbox);
// console.log("Elem after checkbox " + TempElem.innerHTML);
TempElem.innerHTML += " <span class='listitem'> " + TaskList[i] + "</span>";
// console.log("Elem after tasklist "+ TempElem.innerHTML);
TempElem.appendChild(btnUp);
TempElem.appendChild(btnDown);
console.log("Final Tepelem " + TempElem.innerHTML);
list.appendChild(TempElem);
}
}
Because you are appending the same element so since the same element can not be in more than one place it is moved to the new location. You need to clone them before appending.
https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
TempElem.appendChild(checkbox.cloneNode(true));
You need to do it to the buttons also.

Add button with function call for generatet table

I´m filling a table with jquery from a JSON data source
var data = dataJSONMOV,
fragment = document.createDocumentFragment(),
tr, td, i, il, key;
for(i=0, il=data.length;i<il;i++) {
tr = document.createElement('tr');
for(key in data[i]) {
td = document.createElement('td');
td.appendChild( document.createTextNode( data[i][key] ) );
tr.appendChild( td );
}
//Button generation code should go here (see below)
fragment.appendChild( tr );
}
$('#mytable tbody').append( fragment.cloneNode(true) );
I want to add a button in the end of each row which calls a function displayInformation(string ID) with a parameter from the first coloumn of that row.
How can I accomplish that?
I tried it with this code but it doesn`t show me any buttons
//Button generation code
var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = data[i][0];
btn.onclick = (getTestAlert(data[i][0]));
tr.appendChild(btn);
You are on right direction on how add the button. You can add it and them add an event listener to the table:
$('#mytable').on("click", "input", function() {
});
// Or
$('#mytable').on("click", "input", getTestAlert);
So, to know what id it belongs, add a data attribute:
var btn = document.createElement('input');
btn.dataset.id = data.id;
And how to retrieve it:
$('#mytable').on("click", "button", function() {
var id = $(this).data("id"); // For jQuery
id = this.dataset.id; // For vanilla
});
Your loop would probably end like this:
for(i=0, il=data.length;i<il;i++) {
tr = document.createElement('tr');
for(key in data[i]) {
td = document.createElement('td');
td.appendChild( document.createTextNode( data[i][key] ) );
tr.appendChild( td );
}
// Add button in last column
var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = data[i][0];
btn.onclick = (getTestAlert(data[i][0]));
tr.appendChild(btn);
fragment.appendChild( tr );
}
Working demo
Besides, I don't know if its some kind of a requirement, but if you're using jQuery, you should use it for your entire code, like the elements creating as well. Creating elements may be odd in some browsers and jQuery takes care of it. If you're interested, your code should became something like:
var data = dataJSONMOV,
fragment = document.createDocumentFragment(),
key, html = "";
for(var i=0, il=data.length;i<il;i++) {
html+= "<tr>";
for(key in data[i]) {
html+= "<td>" + data[i][key] + "</td>";
}
html+= "<td><input type='button' class='btn' value='Click me' data-id='" + data[i].id + "' /></td></tr>";
}
$("#mytable").append(html);
Pretty short, huh ?
Because you're populating the table dynamically, you need to add a click listener based on some parent defined in the html. Assuming this is the case for '#myTable tbody' and that the parameter from the first column of that row that you need for displayInformation() is accessible via .text(), you could use
$(document).ready(function() {
$('#myTable tbody').on('click', 'input[type="button"]', function() {
displayInformation($('td:first-child', $(this).parents('tr')).text());
});
});
to create the click listener for the row's button.

Bind jquery datepicker to dynamic row Textfield

In HTML table, there is a text field on which I have binded Jquery datepicker control:
$("#CreatedOnValue").datepicker();
It works fine. The table is dynamic and user can add as many rows as he wants by clicking on add button adjacent to each row. I am trying to bind datepicker control to dynamic rows as well and it is not working. Here is function which is executed when user clicks on row add button:
function addGroupRow(e) {
var rowId = e.parentNode.parentNode.id;
var newindex = getConditionPlacementIndex(rowId);
var row = document.getElementById("advancedSearch").insertRow(newindex);
...
// create table cell of datetime textbox
var cell3 = row.insertCell(3);
cell3.id = row.id+"_cell3";
var strHtml3 = "<INPUT class=\"textbox\" TYPE=\"text\">";
cell3.innerHTML = strHtml3.replace(/!count!/g, count);
$("#" + cell3.id).datepicker();
}
Its not working and datepicker does not appear on dynamic text field. Any suggestion?
Thanks.
Use class instead of id(Give dynamically generated textboxes a class say 'textbox') and do as :
$('body').on('focus',".textbox", function(){
$(this).datepicker();
});​
Working Demo
I have resolved this issue by following code modification:
var cell3 = row.insertCell(3);
var cell3Id = row.id+"_cell3";
var strHtml3 = "<INPUT class=\"textbox\" TYPE=\"text\" id=" + cell3Id + ">";
cell3.innerHTML = strHtml3.replace(/!count!/g, count);
$("#" + cell3Id).datepicker();

jQuery: dialog() of table data from ajax not showing

$(function () {
$('.referral').on('click', function () {
$('#hold').html($(this).find('DIV').html());
$('#hold').dialog();
});
});
$(function getTableData() {
$.ajax({
url: 'interface_API.php',
data: "",
dataType: 'json',
success: function (data) {
setTimeout(function () {
getTableData()
}, 1000);
var body = document.getElementById('tbody');
body.innerHTML = '';
for (var i in data) {
var row = data[i];
var customerCode = row.CustomerCode;
var phone = row.PhoneNumber;
var thetime = row.TimeStamp;
var tr = document.createElement('TR');
tr.className += " " + "referral";
body.appendChild(tr);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(customerCode));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(phone));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(thetime));
tr.appendChild(td);
var tr2 = document.createElement('TR');
body.appendChild(tr2);
var td2 = document.createElement('TD');
var divE = document.createElement('DIV');
divE.className += " " + "extra";
var text = document.createTextNode("sage, extra, etc");
divE.appendChild(text);
td2.appendChild(divE);
tr2.appendChild(td2);
}
}
});
});
I have data from a JSON api that is imported using ajax.
This is displayed to a table, of which the rows are created using JS.
With each row, there is an additional row of 'additional' data that is hidden from the user.
on click of a row, i wish for a dialog to appear displaying this 'additional' data.
Initally i tryed todo this with writing out the rows in "raw format" (var row = "<tr><td>...</td></tr>" etc) however i read that this does not work well with javascript functions like the one i am trying to execute as the DOM has already been set (i'm not 100% sure about that). This is why i use JS to create each element & do it correctly, to some respect.
However, i am still unable to get the dialog to appear
Notes.
below the table (html hard coded) is a empty div which is used as a holder for when a dialog is to appear.
I have had success before when the data is static & ajax is not involved
I found the solution.
It seems that the JS .on('click', function() was not being called, or registered at the right point. i checked on the DOM properties using chrome dev tools & .referral's onclick property was null.
Instead, i set the onclick attribute of each <TR> with the function clicks() like so:
var tr = document.createElement('TR');
tr.setAttribute("onclick", "clicks(this)");
With,
function clicks(param){
$('#hold').html($(param).find('DIV').html());
$('#hold').dialog();
};

Categories

Resources