I am creating a javascript based "favourite assignment" list for my photo app which I have created using phonegap.
I'm basing it on a "to-do list" tutorial code and have tried to adapt it to my purposes.
There are two variables: the title (text) and the link (text2)
It works great in a browser, and on first launch in the app.
But on refresh or relaunch, I dont think it's saving the link variable to the dictionary.
would appreciate any guidance with the code:
<script type="text/javascript" language="JavaScript">
//Create a new To-Do
function createNewToDo()
{
var todoDictionary = {};
//Prompt the user to enter To-Do
var todo="FAST SHUTTER SPEEDS";
var todolink="#fastshutter";
if (todo!=null)
{
if (todo == "")
{
alert("To-Do can't be empty!");
}
else
{
//Append the new To-Do with the table
todoDictionary = { check : 0 , text : todo , text2 : todolink};
addTableRow(todoDictionary,false);
}
}
}
//Add a row to the table
var rowID = 0;
function addTableRow(todoDictionary, appIsLoading)
{
rowID +=1;
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//Set up the CheckBox
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "deleteButton";
element1.value = "X";
element1.setAttribute("onclick","deleteSelectedRow(this)");
element1.className = "deleteButton";
cell1.appendChild(element1);
//Set up the View Button
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "viewButton";
element2.value = todoDictionary["text"];
var link = todoDictionary["text2"];
element2.id = rowID;
element2.onclick=function(){ window.location.hash = link; };
element2.className = "viewButton";
cell2.appendChild(element2);
//Save & Update UI
saveToDoList();
if (!appIsLoading)
alert("Assignment Added To Favourite List!");
}
//Deletes current row
function deleteSelectedRow(deleteButton)
{
var p=deleteButton.parentNode.parentNode;
p.parentNode.removeChild(p);
saveToDoList();
}
function saveToDoList()
{
//Create a todoArray
var todoArray = {};
var checkBoxState = 0;
var textValue = "";
var text2Value = "";
//Get current table
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount != 0)
{
//Loop through all rows
for(var i=0; i<rowCount; i++)
{
var row = table.rows[i];
//Add checkbox state
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
checkBoxState = 1;
}
else
{
checkBoxState= 0;
}
//Add text data
var textbox = row.cells[1].childNodes[0];
textValue = textbox.value;
//Fill the array with check & text data
todoArray["row"+i] =
{
check : checkBoxState,
text : textValue
};
}
}
else
{
todoArray = null;
}
//Use local storage to persist data
//We use JSON to preserve objects
window.localStorage.setItem("todoList", JSON.stringify(todoArray));
}
function loadToDoList()
{
//Get the saved To-Do list array by JSON parsing localStorage
var theList = JSON.parse(window.localStorage.getItem("todoList"));
if (null == theList || theList=="null")
{
deleteAllRows();
}
else
{
var count = 0;
for (var obj in theList)
{
count++;
}
//Clear table
deleteAllRows();
//Loop through all rows
for(var i=0; i<count; i++)
{
//Add row
addTableRow(theList["row"+i],true);
}
}
}
It appears that in the saveToDoList function you aren't adding your text2 value to the array of objects that's saved to localStorage:
todoArray["row"+i] =
{
check : checkBoxState,
text : textValue
};
Should be:
todoArray["row"+i] =
{
check : checkBoxState,
text : textValue,
link : // get the value of your link
};
Since you haven't posted the associated HTML I cannot tell you how to get the value of the link
Related
I'm developing a test build for my project, which includes a lot of data manipulation. I have two buttons inline at the end of the rows, one for editing, and one for committing the changes made.
function editRow(btn) {
var row = btn.parentNode.parentNode;
row.contentEditable = "true";
row.focus();
}
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
//create rows
var newRow = tbl.insertRow(-1);
var i;
for (i = 0; i < numberOfCells; i++) {
newRow.insertCell(0);
}
//assignbuttons
var lastcell = newRow.cells[numberOfCells - 1];
addEditButton(lastcell);
addCommitButton(lastcell);
}
function addEditButton(context) {
var button = document.createElement("input");
button.type = "button";
button.value = "Edit";
button.onclick = editRow(this);
context.appendChild(button);
}
The user will press the new row button, and then an empty row will appear along with the two buttons.
I am getting the error:
Uncaught TypeError: Cannot read property 'parentNode' of undefined
at editRow (js.js:97)
at addEditButton (js.js:123)
at addRow (js.js:115)
at HTMLButtonElement.onclick (index.html:36)
There are 2 problems I can see.
button.onclick = editRow(this); the this would result in undefined (in strict mode) in that scope. You can probably fix this by sending in the button element
button.onclick = editRow(button);
More reading on this in a function scope
Also you are not creating a row with a td element to place the button in. So btn.parentNode.parentNode is not the row element as you are expecting
Try this
function editRow(btn) {
var row = btn.parentNode.parentNode;
row.contentEditable = "true";
row.focus();
}
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
//create rows
var newRow = tbl.insertRow(-1);
var i;
for (i = 0; i < numberOfCells; i++) {
newRow.insertCell(0);
}
//assignbuttons
var lastcell = newRow.cells[numberOfCells - 1];
addEditButton(lastcell);
//addCommitButton(lastcell);
}
function addEditButton(context) {
var row = document.createElement("row");
var td = document.createElement("td");
var button = document.createElement("input");
button.type = "button";
button.value = "Edit";
td.appendChild(button);
row.appendChild(td);
context.appendChild(row);
button.onclick = editRow(button);
}
addRow("myTable", 2)
<table id="myTable">
</table>
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
var tableHTML = $("#" + tableID).html();
if(numberOfCells === 5) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
if(numberOfCells === 4) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
if(numberOfCells === 3) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
}
I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});
A excel CSV (comma seperated value) file is uploaded initially. This CSV file is represented as a table format in an html page. Here, I need to add a radio button, button etc,along with the table formatted representation. Is this possible without usage of database?.
Thanks in advance.
function Upload() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var radio = document.createElement("radio");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
dvCSV.appendChild(radio);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
I had created an element 'radio' inside function also appended as a child, but it doesn't displays it. My requirement is that, when each row of CSV file is placed, I need to place a radio and button there.(radio for selecting and button for editing the row element and save file).
This line
var radio = document.createElement("radio");
means <radio></radio>. However, there is no radio tag. It's <input type="radio">:
var radio = document.createElement("input");
radio.type = 'radio';
To "group" all radio buttons together, you also need to give them the same name:
radio.name = 'radio';
And if you say you need a button too, then create one:
var button = document.createElement('button');
button.textContent = 'Click me';
But most importantly, if you need them for every row, then put them there, and not somewhere else:
reader.onload = function(e)
{
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for(var i = 0; i < rows.length; i++)
{
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for(var j = 0; j < cells.length; j++)
{
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
// Here:
var radio = document.createElement("input");
radio.type = 'radio';
radio.name = 'radio';
var button = document.createElement('button');
button.textContent = 'Click me';
var cell = row.insertCell(-1);
cell.appendChild(radio);
cell.appendChild(button);
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
So this is a bit complex
I have created an app using phonegap. I am trying to implement a "to-do" list.
I have found a great example javascript method, which I have put into the main index.html document.
So when the app first launches, it works fine and looks the way it's supposed to:
it lets me add new to dos, check a bunch to remove, or hit a button to delete them, etc.
but when I close the app and re-load it, it loses all the styling and the delete buttons no longer functions:
but, it I click ADD ITEM, the new items show in the style they are supposed to...
So, here is the code in the index.html head for the scripts:
<script type="text/javascript" language="JavaScript">
//Create a new To-Do
function createNewToDo()
{
var todoDictionary = {};
//Prompt the user to enter To-Do
var todo="ASSIGNMENT NAME";
var todolink="index.html#fastshutter";
if (todo!=null)
{
if (todo == "")
{
alert("To-Do can't be empty!");
}
else
{
//Append the new To-Do with the table
todoDictionary = { check : 0 , text : todo , text2 : todolink};
addTableRow(todoDictionary,false);
}
}
}
//Add a row to the table
var rowID = 0;
function addTableRow(todoDictionary, appIsLoading)
{
rowID +=1;
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//Set up the CheckBox
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
element1.checked = todoDictionary["check"];
element1.setAttribute("onclick","checkboxClicked()");
element1.className = "checkbox";
cell1.appendChild(element1);
//Set up the TextBox
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.size = 16;
element2.id = "text"+rowID;
element2.value = todoDictionary["text"];
element2.setAttribute("onchange","saveToDoList()");
element2.className = "textbox";
cell2.appendChild(element2);
//Set up the View Button
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "button";
element3.id = rowID;
element2.value = todoDictionary["text"];
element3.setAttribute("onclick","window.open('index.html#fastshutter','_self')");
element3.className = "viewButton";
cell3.appendChild(element3);
//Set up the Delete Button
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "button";
element4.setAttribute("onclick","deleteSelectedRow(this)");
element4.className = "deleteButton";
cell4.appendChild(element4);
//Save & Update UI
checkboxClicked();
saveToDoList();
if (!appIsLoading)
alert("Task Added Successfully.");
}
//Add storke to completed tasks text
function checkboxClicked()
{
//Get current table
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
//Loop through all rows
for(var i=0; i<rowCount; i++)
{
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
var textbox = row.cells[1].childNodes[0];
//checkbox is checked
if(null != chkbox && true == chkbox.checked)
{
if(null != textbox)
{
textbox.style.setProperty("text-decoration", "line-through");
}
}
//checkbox is not checked
else
{
textbox.style.setProperty("text-decoration", "none");
}
}
//Save
saveToDoList();
}
//Views textField's content of the selected row
function viewSelectedRow(todoTextField)
{
alert(todoTextField.value);
}
//Deletes current row
function deleteSelectedRow(deleteButton)
{
var p=deleteButton.parentNode.parentNode;
p.parentNode.removeChild(p);
saveToDoList();
}
function removeCompletedTasks()
{
//Get current table
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
//Loop through all rows
for(var i=0; i<rowCount; i++)
{
//Delete row if checkbox is checked
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
table.deleteRow(i);
rowCount--;
i--;
}
}
//Save
saveToDoList();
alert("Completed Tasks Were Removed Successfully.");
}
function saveToDoList()
{
//Create a todoArray
var todoArray = {};
var checkBoxState = 0;
var textValue = "";
//Get current table
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount != 0)
{
//Loop through all rows
for(var i=0; i<rowCount; i++)
{
var row = table.rows[i];
//Add checkbox state
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
checkBoxState = 1;
}
else
{
checkBoxState= 0;
}
//Add text data
var textbox = row.cells[1].childNodes[0];
textValue = textbox.value;
//Fill the array with check & text data
todoArray["row"+i] =
{
check : checkBoxState,
text : textValue
};
}
}
else
{
todoArray = null;
}
//Use local storage to persist data
//We use JSON to preserve objects
window.localStorage.setItem("todoList", JSON.stringify(todoArray));
}
function loadToDoList()
{
//Get the saved To-Do list array by JSON parsing localStorage
var theList = JSON.parse(window.localStorage.getItem("todoList"));
if (null == theList || theList=="null")
{
deleteAllRows();
}
else
{
var count = 0;
for (var obj in theList)
{
count++;
}
//Clear table
deleteAllRows();
//Loop through all rows
for(var i=0; i<count; i++)
{
//Add row
addTableRow(theList["row"+i],true);
}
}
}
function deleteAllRows()
{
//Get current table
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
//Loop through all rows
for(var i=0; i<rowCount; i++)
{
//delete row
table.deleteRow(i);
rowCount--;
i--;
}
//Save
saveToDoList();
}
</script>
and the style (also in the head)
<style type="text/css">
/* BeginOAWidget_Instance_2127022: #gallery */
.viewButton {
background-color:Transparent;
width:50px
height:32px;
}
.deleteButton {
background-color:Transparent;
width:30px;
height:30px;
}
Here is the html code to implement the page:
<body bgcolor="#e0e0e0" onload="loadToDoList()" >
<div data-role="page" id="favlist">
<div data-role="header">
<h1>BACK Favourites </h1>
</div>
<div data-role="content">
<button type="button" class="addToDo" onclick="createNewToDo()">ADD</button>
<button type="button" class="removeTasks" onclick="removeCompletedTasks()">REMOVE</button>
<br/><br/><br/>
<table id="dataTable" width="100%" border="0">
</table>
CLOSE
</div>
</div>
So I'm not sure if the jquerymobile css file is interfering with this maybe?
Thanks for any advice
EDIT: I was able to figure it out. I needed to override the jquery mobile CSS completely for the button elements by adding a new button class to the jquery css. On first run and adding new items it used the inline styles I had put in the HTML, but on reload it was pulling the standard styles
I was able to figure it out. I needed to override the jquery mobile CSS completely for the button elements by adding a new button class to the jquery css. On first run and adding new items it used the inline styles I had put in the HTML, but on reload it was pulling the standard styles
I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name