DOM sorting column// strikethrough on click - javascript

I want to sort the values from input under Item Description (alphabetically and reverse) and also strike-through when click "Mark as buy" (button that I need it under "Actions")
https://codepen.io/iacob24/pen/MBYzXm
var sortingDirection;
var lista = [];
function addProduct() {
document.getElementById('itemsActions').style.display = "block";
var product = document.querySelector('.product').value;
var btn1 = document.createElement('Button');
document.body.appendChild(btn1);
var x = document.createTextNode("Mark as buy");
btn1.appendChild(x);
var table = document.getElementById('myTable');
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
document.getElementById('input').value = "";
cell1.innerHTML = product;
cell2.appendChild(btn1);
lista.push({
product, btn1
});
btn1.addEventListener("click", function markAsBuy(line) {
var line = document.getElementsByClassName('td1')
for (var i = 0; i < line.length; i++) {
line[i].style.setProperty("text-decoration", "line-thgrough");
}
})
}
function sortAsc() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
while (switching) {
switching = false;
rows = table.getElementsByTagName
}
}
function sortDesc() {
lista.sort();
lista.reverse();
document.getElementsByTagName("th").innerHTML = th1;
}
var input = document.getElementById("input");
input.addEventListener("keyup", function (addProduct) {
addProduct.preventDefault();
if (event.keyCode === 13) {
document.getElementById("Button").click();
}
});

I have attached the codepen link! Click here
Here is the sample function
function addProduct() {
count++;
document.getElementById('itemsActions').style.display = "block";
var product = document.querySelector('.product').value;
var btn1 = document.createElement('Button');
btn1.id="btn"+count;
var x = document.createTextNode("Mark as buy");
btn1.appendChild(x);
var table = document.getElementById('body');
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
document.getElementById('input').value = "";
cell1.innerHTML = product;
cell1.id="product"+count;
cell2.appendChild(btn1);
lista.push(product);
btn1.addEventListener("click", function() {
var id = this.id;
var idNum = id.slice(-1)
var data = document.getElementById('product'+idNum)
data.style.setProperty("text-decoration", "line-through");
})
}
function sortAsc() {
lista.sort();
var tr = document.getElementsByTagName('tr');
for(i=0;i<lista.length;i++){
//to skip the first row do i+1
tr[i+1].getElementsByTagName('td')[0].innerHTML=lista[i]
}
}
function sortDesc() {
lista.sort();
lista.reverse();
var tr = document.getElementsByTagName('tr');
for(i=0;i<lista.length;i++){
//to skip the first row do i+1
tr[i+1].getElementsByTagName('td')[0].innerHTML=lista[i]
}
}

Related

Javascript generated table - How to update other cells in a row when a number input value in this row changes

I am facing a problem for this day I am creating a pop-up cart with a table, I create an array with
ID | NAME | QUANTITY | PRICE
then I generate the table from this array with javascript.My problem is I want to be able to update the price and the total when I change the quantity for a specific item line (= quantity in the table row). This should work for all generated table rows.
This is my javascript code:
var cartCount = 0;
var Total = 0;
var id = 1;
var labels = ['Name', 'Quantity', 'Price'];
var items;
var cartElement = document.getElementById('cartDisplay');
var counterElement = document.getElementById('counterDisplay');
function cartClick(name, quantity, price) {
const x = {
id: id,
name: name,
quantity: quantity,
price: price
};
if (Obj.some(e => e.name === x.name)) {
console.log('already there');
} else {
Obj.push(x);
cartCount = cartCount + 1;
Total = Total + x.price;
id = id +1;
buildTable(labels, Obj, document.getElementById('modalBODY'));
items = Obj;
console.log(items);
}
CheckCart(cartCount);
console.log(cartCount);
}
function CheckCart(counter) {
if (counter > 0) {
cartElement.style.display = "block";
counterElement.innerHTML = counter;
} else {
cartElement.style.display = "none";
}
}
function buildTable(labels, objects, container) {
container.innerHTML = '';
var table = document.createElement('table');
// class table
table.classList.add("cartTable");
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var theadTr = document.createElement('tr');
for (var i = 0; i < labels.length; i++) {
var theadTh = document.createElement('th');
theadTh.classList.add("cartTh");
theadTh.setAttribute("colSpan", "2");
theadTh.style.padding = '12px';
theadTh.innerHTML = labels[i];
theadTr.appendChild(theadTh);
}
thead.appendChild(theadTr);
table.appendChild(thead);
for (j = 0; j < objects.length; j++) {
var tbodyTr = document.createElement('tr');
for (k = 0; k < labels.length; k++) {
var tbodyTd = document.createElement('td');
tbodyTd.classList.add("cartTd");
tbodyTd.setAttribute("colSpan", "2");
tbodyTd.style.padding = '12px';
if (labels[k] === "Quantity") {
var qinput = document.createElement('input');
qinput.setAttribute("type", "number");
qinput.setAttribute("min", "0");
qinput.setAttribute("max", "10");
qinput.setAttribute("id", "quantityInput");
qinput.setAttribute("value", objects[j][labels[k].toLowerCase()]);
tbodyTd.appendChild(qinput);
} else {
tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
}
tbodyTr.appendChild(tbodyTd);
}
tbody.appendChild(tbodyTr);
}
table.appendChild(tbody);
var tfoot = document.createElement('tfoot');
var footTr = document.createElement('tr');
var footTh = document.createElement('th');
var footTd = document.createElement('td');
footTd.setAttribute("id", "totalElement")
tbodyTd.setAttribute("colSpan", "3");
footTh.setAttribute("colSpan", "4");
footTd.innerHTML = Total;
footTh.innerHTML = 'TOTAL';
footTd.classList.add("cartTd");
footTd.classList.add("footerTable");
footTh.classList.add("cartTh");
footTr.appendChild(footTh);
footTr.appendChild(footTd);
tfoot.appendChild(footTr);
table.appendChild(tfoot);
container.appendChild(table);
var beforeText = document.createElement("p");
beforeText.style.marginTop = '5px';
beforeText.innerHTML = "Requests";
container.appendChild(beforeText);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.style.width = '100%';
input.style.padding = '6px';
input.setAttribute("placeholder", "No onion, no tomato...");
container.appendChild(input);
}
I solved a similar problem by creating a rowid and when the user clicks into the row I check for changes. Here the main idea
tableRow.setAttribute("id", "row" + idTable + "_" + tableRow.rowIndex); // for easy handling and selecting rows
tableRow.addEventListener("click", function(){ ... here check for what ever change});
You could also go for a specific change in just one cell, so attach the eventlistener to each quantity cell and read the new value, validate and update other fields then
qinput.addEventListener("change", function(){ ... here check for what ever the change triggers });
EDIT fortheOP:
A generic example for adding an event listener to a tablerow this marks the selected table line red (class table-danger) and removes the colour from allother previous selected lines:
tableRow.addEventListener("click", function(){
tRowData = [];
if(this.classList.contains("table-danger")) {
this.classList.remove("table-danger");
return;
} else {
var nodeParent = this.parentNode;
var trows= nodeParent.getElementsByTagName("tr");
for(var i = 0; i < trows.length;i++) {
trows[i].classList.remove("table-danger");
}
this.classList.add("table-danger");
var cells = this.getElementsByTagName("td");
for ( i = 0; i < cells.length; i++) {
tRowData.push(cells[i].innerHTML); // e.g.: Here you could place your update routine
}
tRowData.push(this.getAttribute("id"));
tRowData.push(this.rowIndex);
return tRowData;
}
});

While displaying its also print old Data from local storage

function addrow() {
debugger;
var person = [];
if (localStorage.person1 != null && localStorage.person1 !=undefined) {
var person = JSON.parse(localStorage.person1);
}
var name = document.getElementById('name').value;
var city = document.getElementById('city').value;
person.push({
pname: name,
pcity: city
});
localStorage.setItem('person1', JSON.stringify(person));
bind();
}
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
for (i = 0; i < per_list.length; i++ ) {
var table = document.getElementById('ptable');
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}
I have two fields name and city;Now, click on "add row" prints ok for first value, but afterwards it is printing both old and new value.. And, i want only new entry below the old input.. thanks in advance
You need to clear the table since you are showing all the elements in the .bind function.
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
// clear the table
var table = document.getElementById('ptable');
for (var i = 0, rows = table.rows.length; i < rows; i++) {
table.deleteRow(0)
}
// fill the table
for (i = 0; i < per_list.length; i++) {
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}

Why my selecting data only show the last data?

why i cannot select the first data and the second data when i tested using console.log
This is the table:
var ref = firebase.database().ref("recommendations");
ref.on("value", function(snapshot) {
// console.log(snapshot.val());
var recommendations = snapshot.val();
var keys = Object.keys(recommendations);
console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var title = recommendations[k].title;
var link = recommendations[k].link;
var presenter = recommendations[k].presenter;
// document.getElementById('title').innerHTML = title;
// document.getElementById('presenter').innerHTML = presenter;
// document.getElementById('link').innerHTML = link;
var table = document.getElementById("data");
var tr = document.createElement('tr');
var td1 = tr.appendChild(document.createElement('td'));
var td2= tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
var tdEdit = tr.appendChild(document.createElement('td'));
td1.innerHTML = title;
td2.innerHTML = presenter;
td3.innerHTML = link;
tdEdit.innerHTML = "<button id='"+k+"' class='btn btn-default edit'>Edit</button>";
table.appendChild(tr);
}
$(document).ready(function() {
$(".edit").on("click", function(){
console.log(k);
})
});
});
The issue is that you log k which is a reference to inside the loop. So the loop go's key0 key1 key2 and stays key2 because thats the last value of k.
Use something like:
$(document).ready(function() {
$(".edit").on("click", function(){
// From the button perspective this references the Native element.
console.log(this.id); // or $(this).attr("id")
})
});

adding row to an existing table in javascript

guys i jnow it is dummy question but i spent hours in this and cant reach .. i want to add row to an existing table and this row consists of checkbox and 4 textboxes .. when i run it the textboxes appears but the checkbox dont .. here is my code
function addRow() {
var i = 1;
var table = document.getElementById("table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var html = [];
html.push("<table id='table'>\n<body>");
html.push("<tr><td><input type='checkbox' name='chk'/></td>");
var cell = row.insertCell(html);
for ( var propertyNames in grid.data[0]) {
cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.size = 10;
element.name = "input"+i;
cell.appendChild(element);
html.push("<td>" + cell + "</td>");
i++;
}
html.push("</tr>");
html.push("</body>\n</table>");
}
The problem is you are creating a array with the markup for the checkbox, but it is never added to the table
function addRow() {
var i = 1;
var table = document.getElementById("table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell = row.insertCell();
var element = document.createElement("input");
element.type = "checkbox";
element.name = "chk";
cell.appendChild(element);
for (var propertyNames in grid.data[0]) {
cell = row.insertCell(i);
element = document.createElement("input");
element.type = "text";
element.size = 10;
element.name = "input" + i;
cell.appendChild(element);
i++;
}
}
var grid = {
data: [{
x: 1,
y: 1
}]
};
addRow();
<table id="table"></table>

why the onclick event doen't work from an external .js file?

I have wrote a .js file in wich I have create a table, buttons, etc. My aplication is a photo album and everything is created on this file, the html build up properly with all the buttons but when I give click on the buttons, the buttons don't change the images.
The code of the .jp file is:
var dp = document.createElement("img");
function changeImage()
{
var list = document.getElementById('optionlist');
dp.src = list.options[list.selectedIndex].value;
alert(dp.src);
}
function prevImage()
{
var list = document.getElementById('optionlist');
alert("Llega a prev");
if(list.selectedIndex == 0)
{
list.selectedIndex = list.options.length-1;
}
else
{
list.selectedIndex--;
}
changeImage();
}
function firstImage()
{
var list = document.getElementById('optionlist');
list.selectedIndex = 0;
changeImage();
}
function nextImage()
{
var list = document.getElementById('optionlist');
if(list.selectedIndex == list.options.length-1)
{
list.selectedIndex = 0;
}
else
{
list.selectedIndex++;
}
changeImage();
}
function lastImage()
{
var list = document.getElementById('optionlist');
list.selectedIndex = 9;
changeImage();
}
function start() {
var txt1,txt2,txt3,txt4,txt5,txt6,txt7,txt8,txt9,txt10,txt11;
//get the reference for the body
var body = document.getElementsByTagName("body")[0];
//alert("creates a <table> element and a <tbody> element");
var tbl = document.createElement("table");
tbl.setAttribute("align","center");
tbl.setAttribute("border","0");
var tbl2 = document.createElement("table");
tbl2.setAttribute("align","center");
tbl2.setAttribute("border","0");
var tblBody = document.createElement("tbody");
var tblBody2 = document.createElement("tbody");
//alert("creating <p>");
txt11 = document.createTextNode(" JavaScript Module ");
var downtxt = document.createElement("p");
downtxt.setAttribute("align","center");
downtxt.appendChild(txt11);
//alert("creates <input> elements");
var first = document.createElement("input");
first.setAttribute("value", " << ");
first.setAttribute("type", "button");
first.onClick = firstImage;
var previous = document.createElement("input");
previous.setAttribute("type", "button");
previous.setAttribute("value", " < ");
previous.onClick = "JavaScript:prevImage()";
var last = document.createElement("input");
last.setAttribute("value", " >> ");
last.setAttribute("type", "button");
last.onClick = "JavaScript:lastImage()";
var next = document.createElement("input");
next.setAttribute("value", " > ");
next.setAttribute("type", "button");
next.onClick = "JavaScript:nextImage()";
//alert("creating images options and <select>");
var op1 = document.createElement("option");
var op2 = document.createElement("option");
var op3 = document.createElement("option");
var op4 = document.createElement("option");
var op5 = document.createElement("option");
var op6 = document.createElement("option");
var op7 = document.createElement("option");
var op8 = document.createElement("option");
var op9 = document.createElement("option");
var op10 = document.createElement("option");
op1.setAttribute("value","1.jpg");
txt1 = document.createTextNode("First Image");
op1.appendChild(txt1);
op2.setAttribute("value","2.jpg");
txt2 = document.createTextNode("Second Image");
op2.appendChild(txt2);
op3.setAttribute("value","3.jpg");
txt3 = document.createTextNode("Third Image");
op3.appendChild(txt3);
op4.setAttribute("value","4.jpg");
txt4 = document.createTextNode("Fourth Image");
op4.appendChild(txt4);
op5.setAttribute("value","5.jpg");
txt5 = document.createTextNode("Fifth Image");
op5.appendChild(txt5);
op6.setAttribute("value","6.jpg");;
txt6 = document.createTextNode("Sixth Image");
op6.appendChild(txt6);
op7.setAttribute("value","7.jpg");
txt7 = document.createTextNode("Seventh Image");
op7.appendChild(txt7);
op8.setAttribute("value","8.jpg");
txt8 = document.createTextNode("Eight Image");
op8.appendChild(txt8);
op9.setAttribute("value","9.jpg");
txt9 = document.createTextNode("Ninth Image");
op9.appendChild(txt9);
op10.setAttribute("value","10.jpg");
txt10 = document.createTextNode("Tenth Image");
op10.appendChild(txt10);
var slct = document.createElement("select");
slct.setAttribute("id","optionlist");
slct.onChange = changeImage;
slct.appendChild(op1);
slct.appendChild(op2);
slct.appendChild(op3);
slct.appendChild(op4);
slct.appendChild(op5);
slct.appendChild(op6);
slct.appendChild(op7);
slct.appendChild(op8);
slct.appendChild(op9);
slct.appendChild(op10);
//alert("Creating rows and columns for the tables");
var td1 = document.createElement("td");
td1.setAttribute("align","center");
td1.setAttribute("colspan","3");
dp.setAttribute("name","mainimage");
dp.setAttribute("border","1");
dp.setAttribute("align","center");
td1.appendChild(dp);
var tr1 = document.createElement("tr");
tr1.setAttribute("align","center");
tr1.appendChild(td1);
var td2 = document.createElement("td");
td2.setAttribute("align","left");
td2.appendChild(first);
td2.appendChild(previous);
var td3 = document.createElement("td");
td3.setAttribute("align","center");
td3.appendChild(slct);
var td4 = document.createElement("td");
td4.setAttribute("align","right");
td4.appendChild(next);
td4.appendChild(last);
var tr2 = document.createElement("tr");
tr2.appendChild(td2);
tr2.appendChild(td3);
tr2.appendChild(td4);
//alert("adding all the elements to the table");
tblBody2.appendChild(tr1);
tblBody.appendChild(tr2);
tbl2.appendChild(tblBody2);
tbl.appendChild(tblBody);
//alert("adding table to <body>");
body.appendChild(tbl2);
body.appendChild(tbl);
body.appendChild(downtxt);
changeImage();
}
and the html code is:
<html>
<head>
<title>Photo Album </title>
<style>
p, td {color:blue;font-family:verdana;font-size:8pt}
h1 {color:black;font-family:verdana;font-size:14pt}
</style>
<script type = "text/javascript" src = "PAScript.js" language = "javascript">
</script>
</head>
<body onLoad="start()" bgcolor = "grey">
</body>
</html>
It somebody can help me please, I don't have idea how to make work the buttons of my application
Thanks
When you're setting onclick by javascript, it's a function reference instead of a string.
previous.onClick = "JavaScript:prevImage()";
should be
previous.onclick = prevImage;
Fix your other assignments to follow this pattern. Also onclick is all lower case and is case sensitive.
As long as we're on the topic, the preferred way to register event handlers is
standards compliant browsers
previous.addEventListener('click', prevImage, false);
IE
previous.attachEvent('onclick', prevImage);

Categories

Resources