How to click and edit each of the html cells in JavaScript - javascript

window.onload = function() {
var r = 0,
c = 0;
for (x in localStorage) {
var row = table.insertRow(r),
obj = JSON.parse(localStorage.getItem(x));
for (i in obj) {
var cell = row.insertCell(c);
cell.innerHTML = obj[i];
c += 1
}
r += 1;
c = 0;
}
for (var a = 0; a < table.length; a += 1) {
}
table.rows[a].cells[0].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
table.rows[a].cells[1].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
table.rows[a].cells[2].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
table.rows[a].cells[3].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
};
This code on load loops through the saved local storage JSON objects and then prints them into a table each object takes a row and the values are in the cells what i want is to be able to click and edit each of these rows this code only works for the first row and not the others so what should i do?

Put your code inside the for loop
for (var a = 0; a < table.length; a++) {
table.rows[a].cells[0].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
table.rows[a].cells[1].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
//more table.rows.....
}
Using jQuery is very simple:
$(function(){
$('table td').click(function(){
var ask = prompt("Input");
$(this).html(ask);
});
});

You add event outside of the loop
for (var a = 0; a < table.length; a += 1) {
for(var j=0;j<3;j++){
table.rows[a].cells[j].addEventListener('click', function() {
var ask = prompt("Input");
this.innerHTML = ask;
});
}
}

Related

cells/rows are inserted under the first column

I'm working on a real-time timetable for a school, for that I've an admin panel with a side "User verwalten" (manage users) where I manage the rights and permissions of the individual users. I want to create a table with the name and checkbox where you can mark the rights with a cross.
The data for this(all users and there permissions) are located on a webserver.
The Problem:
Now I have added the table-header and I want to add the users. But now with the table-header everything gets added in the first column and I dont know why. When I debugged, it is found that the cells are added in the right row but if I add the row it looks like this:
But i want it to look like this but with a table-header:
Here is the code for createTable()
function createTable(json){
var obj = JSON.parse(json);
var oldBody = document.getElementsByTagName('tbody')[0];
var body = document.createElement('tbody');
//if i add this header everything gets desroyed
//var header = document.getElementById("header").innerHTML = '<tr><th class="header"><h3>Name</h3></th><th class="header"><h3>Schüler verwalten</h3></th><th class="header"><h3>Benutzer verwalten</h3></th><th class="header"><h3>History anschauen</h3></th><th class="header"><h3>Home verwalten</h3></th></tr>';
for (var j = 0; j < obj.length; j++) {
var row = addRow(obj[j]);
row.classList.add('row');
//table.appendChild(body);
}
}
code foraddRow()
function addRow(val) {
var tr = document.createElement('tr');
for( var i = 0; i < 5; i++){
if(i==0){
var name = val.substr(0,(val.length)-9);
addCell(tr, null,name);
}else{
var rest = val.substr((val.length)-9, val.length);
var values = rest.split(";");
addCell(tr, values[i], name);
}
table.appendChild(tr);
}
return tr;
}
code for addCell()
function addCell(tr, val, name) {
var name;
var cell = document.createElement('input');
var value = "get";
if(val == null){
cell.classList.add("name")
cell.value = name;
cell.addEventListener("dblclick", function () {
cell.classList.remove('cell');
cell.classList.add('selected');
clearSelection();
});
}else if(val == 0){
cell.classList.add('checkbox');
cell.type = "checkbox";
cell.checked = false;
cell.addEventListener( 'change', function() {
value += getString();
getData(value);
});
}else if(val == 1){
cell.classList.add('checkbox');
cell.type = "checkbox";
cell.checked = true;
cell.addEventListener( 'change', function() {
value += getString();
getData(value);
});
}
tr.appendChild(cell);
}
I think you need to set a newStartIndex var.
Something like this is what I did. (If I understand correctly)
I realize this might not be exactly what you are asking but perhaps it points you in the right direction.
var ucfIndex = 2;
const ucfSelectedRowIndex = rows.indexOf(feedbackCandidates[x]) + ucfIndex;
var sheets = google.sheets({ version: 'v4' });
authorize(function () {
var request = {
spreadsheetId: 'yourSheetId',
valueInputOption: 'RAW',
resource: {
"data": [
{
"range": "N" + ucfSelectedRowIndex,
"majorDimension": "COLUMNS",
"values": [
[
true
],
]
},
],
},
auth,
};
sheets.spreadsheets.values.batchUpdate(request, function (err, response) {
if (err) {
console.error(err);
return;
}
else {
console.info(response);
console.log("Col Values updated");
};
});
});
Code for Add row
var table = document.getElementById("tbl");
for (var i = 0 ; i < table.rows.length; i++) {
var row = "";
for (var j = 0; j < table.rows[i].cells.length; j++) {
row += table.rows[i].cells[j].innerHTML;
row += " | ";
}
alert(row);
}

duplicate data when searching for a specific value in javascript object

I am using the following code to look for a specific value id in javascript object. I am getting duplicate objects.
This is the javascript code I am using:
$('.seat').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
//SeatId is 1
var categoryArray = jsonData;
var id = $(this).attr('id');
var ticketData, seatLocation;
for (var i = 0; i < categoryArray.length; i++) {
var category = categoryArray[i];
for (var j = 0; j < category.assignments.length; j++) {
if (category.assignments[j].seatId == id) {
ticketData = category;
seatLocation = category.assignments[j];
}
}
}
console.log(ticketData);
console.log(seatLocation);
});
This is how the objecs look like after being parsed:
And this is how the data is being printed:
What am I doing wrong?
Try this way:
$('.seat').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var ticketData = [];
var seatLocation = [];
//SeatId is 1
var categoryArray = jsonData;
var id = $(this).attr('id');
$.each(categoryArray, function (i, cat) {
$.each(cat.assignments, function (j, ass) {
if (ass.seatId == id) {
ticketData = cat;
seatLocation = ass;
}
});
});
console.log(ticketData);
console.log(seatLocation);
});

Save change in custom list display using local storage

I am trying to create a customizable list with links that can be hidden using a class if you click in a button. Also the list have a sortable option that you can move the links on the list, which saves to localstorage.
The problem is that I don't know how to save the class change with the list order in the localstorage if you click the "add/remove" button on each li.
Also, if anyone can help me improve the code I will be grateful, I am a newbie with localstorage and only managed this with a lot of reading in tutorials and documentation.
Here's a working example:
http://codepen.io/RogerHN/pen/EgbOzB
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
list.appendChild(itemsArr[i]);
}
}
}
}
$('.list-block.sortable').on('sort', function () {
var newIdsOrder = [];
$(this).find('li').each(function(){
newIdsOrder.push($(this).attr('data-id'));
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newIdsOrder));
});
You want something like this:
var myApp = new Framework7({
swipePanel: 'left'
});
// Export selectors engine
var $$ = Dom7;
var mainView = myApp.addView('.view-main');
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
var classes = JSON.parse(localStorage.getItem('classes') || '["","","","","","","","","",""]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
itemsArr[i].className = classes[i];
list.appendChild(itemsArr[i]);
// handle [add/remove] thing
if (classes[i] != "") {
$(itemsArr[i]).find(".checky").removeClass("selected");
}
}
}
}
}
$('.list-block.sortable').on('sort', saveInfo);
$(".restore").click(function(e) {
$(".confirm").show();
$(".shadow").show();
});
$(".no,.shadow").click(function(e) {
$(".confirm").hide();
$(".shadow").hide();
});
$(".yes").click(function(e) {
$(".confirm").hide();
});
$(".lbl").click(function(e) {
$(".toggle-text").toggleClass("blue");
$(".restore").toggle();
$(".checky").toggle();
$("li.hidden").toggleClass("visible");
});
$('.checky').click(function() {
if (!$(this).hasClass("selected")) {
$(this).parent().removeClass("hidden").addClass("visible");
}
else {
$(this).parent().addClass("hidden visible");
}
$(this).toggleClass("selected");
saveInfo();
});
function saveInfo() {
var newUserList = [];
var newClassList = [];
$("#linklist").find('li').each(
function() {
newUserList.push($(this).attr('data-id'));
if ($(this).hasClass("hidden")) {
newClassList.push("hidden");
}
else {
newClassList.push("");
}
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newUserList));
localStorage.setItem('classes', JSON.stringify(newClassList));
console.log("saved.");
}
function reset() {
console.log("Removing data from local storage.");
localStorage.setItem('userlist', '["1","2","3","4","5","6","7","8","9","10"]');
localStorage.setItem('classes', '["","","","","","","","","",""]');
window.location.reload(true);
};
Codepen
Technically, I should've added explanation...

Populate form from JSON.parse

I am trying to re-populate a form from some values in localStorage. I can't quite manage the last part to get the loop to populate my name and values.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
var formInput = s[i];
console.log(s[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}
Could I get some pointers please.
Your issue is in this section of code.
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
You are setting s to the length of the jsn array minus 1, then using it as if it were jsn. I think you intended something like this.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i];
console.log(jsn[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}

Refactor two jQuery UI auto-completes to be more Functional & DRY

I have two jQuery UI auto-completes on the same page and I'd like to make the code more "functional" and terse. My background is almost strictly OO and I'd like to get more serious about writing more functional JavaScript.
Both of these functions are properties of an object literal that I'm using to namespace the functions on the page. Right now there is a lot of code that's repeated between the functions and I'd like to use something similar to the "partial application" pattern to reduce the code.
autocomplete 1:
initProject : function(){
var selected = 0;
var suggestions = [];
var projs;
var len;
$("#projectNum").autocomplete({
source : function(req, add){
$.getJSON("projectList.do?method=viewProjectListJSON&contractID=" + req.term, function(data){
//clear the suggestions array
suggestions = [];
projs = data[0];
len = projs.length;
for(var i = 0; i < len; i++){
suggestions.push(projs[i][1]);
};
add(suggestions);
});//end getjson callback
},
minLength : 2,
select : function(){
thisval = $(this).val();
for(var i = 0;i < len; i++){
if(thisval === projs[i][1]){
$("#projectID").val(projs[i][0]);
return;
}
}
}
})
},
autocomplete 2:
initCAU : function(){
var selected = 0;
var suggestions = [];
var caus;
var len;
$("#cauNum").autocomplete({
source : function(req, add){
$.getJSON("cauList.do?method=viewCAUListJSON&cauNumber=" + req.term, function(data){
suggestions = [];
caus = data[0];
len = caus.length;
for(var i = 0; i < len; i++){
suggestions.push(caus[i][1].toString());
};
add(suggestions);
}); //end getjson callback
},
minLength : 2,
select : function(){
thisval = $(this).val();
for(var i = 0;i < len; i++){
if(parseInt(thisval,10) === caus[i][1]){
$("#cauID").val(caus[i][0]);
return;
}
}
}
})
},
//factored-out common code...
var autocompleter = function(urlPrefix, fragment) {
var selected = 0;
var suggestions = [];
var items;
var len;
return ({
minLength: 2,
source: function(req, add) {
$.getJSON(urlPrefix + req.term, function(data) {
suggestions = [];
items = data[0];
len = items.length;
for(var i = 0; i < len; i++) {
suggestions.push(projs[i][1]);
};
add(suggestions);
}); //end JSON callback
}, //end source callback
select: function() {
var thisVal = $(this).val();
for(var i = 0; i < len; i++) {
if(thisVal === items[i][1]) {
$(fragment).val(items[i][0]);
return;
}
}
} //end select callback
});
};
//verbose but clear way to achieve what you were doing before.
var initCAU = function() {
var attachTo = "#cauNum";
var urlPrefix = "cauList.do?method=viewCAUListJSON&cauNumber=";
var fragment = "#cauID";
$(attachTo).autocomplete(autocompleter(urlPrefix, fragment));
};
var initProject = function() {
var attachTo = "#projectNum";
var urlPrefix = "projectList.do?method=viewProjectListJSON&contractID=";
var fragment = "#projectID";
$(attachTo).autocomplete(autocompleter(urlPrefix, fragment));
};

Categories

Resources