How to save added data from HTML Table to SQL (PHPMYADMIN) - javascript

So here is my situation; I'm trying to save the data from the table which is added by filling up the form, I don't know how to save this to my database in phpmyadmin using javascript or ajax. A sample code is deeply appreciated. Thanks! PS: I'm a beginner, I'm just scraping the internet for code and trying to make do of what I get. Please Help :D
<html>
<body>
<div class = "inputfield">
<label>First Name:</label>
<input type="text" id="fname"><br>
<label>Last Name:</label>
<input type="text" id="lname"><br>
<label>Gender:</label>
<select name="gender" id="gender">
<option>Male</option>
<option>Female</option>
</select><br>
<label>HOURS:</label>
<input type="number" min=".5" max="12" step=".5" name="hours" id="hours" placeholder="--.5 to 12--"> <br>
</div>
<div class = "tablefield">
<table class="mtable" id="mtable">
<tr>
<th width="27%">First Name</th>
<th width="27%">Last Name</th>
<th width="15%">Gender</th>
<th width="15%">Hour</th>
<th width="16%">Edit</th>
</tr>
</table>
<table class="sumtable">
<tr><b>
<td class="sum">TOTAL HOURS</td>
<td class="sum1" id="sumtd"></td>
</b></tr>
</table>
</div>
<div class="buttons">
<button type = "button" onclick="add1('mtable')">ADD</button>
<button type = "reset" name="reset" class="btnclr">CLEAR</button>
<button type = "button" name="save" onclick="savefunc()">SAVE</button>
</div>
<input type = "hidden" name="hid1" id="hid1">
<input type = "hidden" name="hid2" id="hid2">
<input type = "hidden" name="hid3" id="hid3">
<input type = "hidden" name="hid4" id="hid4">
<script>
var sum = 0;
function add1(){
"use strict";
var hour1 = document.getElementById("hours").value;
sum = parseFloat(sum)+ parseFloat(hour1);
document.getElementById("sumtd").innerHTML = sum;
var table = document.getElementById("mtable"),rindex2;
var rowCount = table.rows.length;
var row = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var element1 = document.createElement("Button");
element1.type = "button";
element1.name = "btnedit";
element1.innerHTML = "Update";
element1.setAttribute('class','btnedit');
var element2 = document.createElement("Button");
element2.type = "button";
element2.name = "btndel";
element2.innerHTML = "Delete";
element2.setAttribute('class','btndel');
for(var i=0; i<rowCount; i++) {
element1.onclick = function () {
try {
rindex2 = this.parentNode.rowIndex;
sum = parseFloat(sum) - parseFloat(table.rows[rindex2].cells[3].innerHTML);
console.log(rindex2);
this.parentNode.cells[0].innerHTML = document.getElementById("fname").value;
this.parentNode.cells[1].innerHTML = document.getElementById("lname").value;
this.parentNode.cells[2].innerHTML = document.getElementById("gender").value;
this.parentNode.cells[3].innerHTML = document.getElementById("hours").value;
sum = parseFloat(sum) + parseFloat(document.getElementById("hours").value);
document.getElementById("sumtd").innerHTML = sum;
}catch(e){
alert(e);
}};
element2.onclick = function () {
try {
rindex2 = this.parentNode.rowIndex;
console.log(rindex2);
sum = parseFloat(sum) - parseFloat(table.rows[rindex2].cells[3].innerHTML);
document.getElementById("sumtd").innerHTML = sum;
table.deleteRow(rindex2);
}catch(e){
alert(e);
}};
}
td1.innerHTML = document.getElementById("fname").value;
td2.innerHTML = document.getElementById("lname").value;
td3.innerHTML = document.getElementById("gender").value;
td4.innerHTML = document.getElementById("hours").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(element1);
row.appendChild(element2);
table.children[0].appendChild(row);
}
function savefunc(){
var table1 = document.getElementById("mtable");
var hid1 = document.getElementById("hid1").value;
var hid2 = document.getElementById("hid2").value;
var hid3 = document.getElementById("hid3").value;
var hid4 = document.getElementById("hid4").value;
for (var r = 1, n = table1.rows.length; r < n; r++){
var c0 = table1.rows[r].cells[0].innerHTML;
var c1 = table1.rows[r].cells[1].innerHTML;
var c2 = table1.rows[r].cells[2].innerHTML;
var c3 = table1.rows[r].cells[3].innerHTML;
var c4 = table1.rows[r].cells[4].innerHTML;
hid1 = c0;
hid2 = c1;
hid3 = c2;
hid4 = c3;
console.log(hid1);
console.log(hid2);
console.log(hid3);
console.log(hid4);
}
}
</script>
</body>
</html>

I've figure it out. i just include this on the bottom of my loop statement and added a save.php file. Use this as reference https://www.studentstutorial.com/ajax/insert-data
$.ajax({
url: "save.php",
type: "POST",
data: {
fname: hid1,
lname: hid2,
gender: hid3,
hour: hid4
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
alert("Save Successful!");
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});

Related

i have a form to input data in and i want the data to appear at another page from local storage

my problem is I console log the local storage and the inputs appear fine but I can't see them on the other page although at local storage they are stored fine
the form :
<form id="formID">
<div class="Contact__Card">
<div class="Input__Container">
<label for="foodName" class="Label" >Food</label>
<input
name="foodName"
class="Input"
type="text"
placeholder="What would you like to add?"
id="foodName"
required
/>
</div>
<div class="input__Container">
<label for="foodType">Choose Food type:</label>
<select class="Input" id="foodType" name="foodlist">
<option value="Fruit and vegetables">Fruit and vegetables</option>
<option value="Starchy food">Starchy food</option>
<option value="Dairy">Dairy</option>
<option value="Protein">Protein</option>
<option value="Fat">Fat</option>
</select></div>
<div class="Input__Container">
<label for="price" class="Label">price</label>
<input type="text" min="1" step="any" class="Input" id="foodPrice" required/>
</div>
<br>
<div class="Input__Container">
<input type="submit" value="Submit" class="Input"/>
</div>
</div>
</form>
the js file of the form page :
"use strict";
var allFood = [];
function food(foodName, foodType, price) {
this.foodName = foodName;
this.foodType = foodType;
this.price = price;
allFood.push(this);
}
food.prototype.fID = function () {
this.id = Math.floor(1111 + Math.random() * 9999);
};
const formEl = document.getElementById("formID");
formEl.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault();
let foodName = event.target.foodName.value;
let foodType = event.target.foodType.value;
let price = event.target.foodPrice.value;
const newFood = new food(foodName, foodType, price);
newFood.fID();
saveData();
}
function saveData() {
let stringifiedData = JSON.stringify(allFood);
localStorage.setItem("Food", stringifiedData);
}
the table of the other page i want the data to apear in :
<table id="fTable">
<tr id="hdrTable">
</tr>
</table>
the js file of the output page is the issue from the get data function ?:
"use strict";
const fdTable = document.getElementById('fTable');
const tableHead = document.getElementById('hdrTable');
var allFood = [];
function food(foodName, foodType, price) {
this.foodName = foodName;
this.foodType = foodType;
this.price = price;
allFood.push(this);
}
food.prototype.fID = function () {
this.id = Math.floor(1111 + Math.random() * 9999);
};
table();
function table() {
let headerID = document.createElement("th");
headerID.textContent = "ID";
let headerName = document.createElement("th");
headerName.textContent = "Food Name";
let headerType = document.createElement("th");
headerType.textContent = "Type of Food";
let headerPrice = document.createElement("th");
headerPrice.textContent = "price";
hdrTable.appendChild(headerID);
hdrTable.appendChild(headerName);
hdrTable.appendChild(headerType);
hdrTable.appendChild(headerPrice);
}
food.prototype.Render = function () {
let row = document.createElement("tr");
let id = document.createElement("td");
let name = document.createElement("td");
let type = document.createElement("td");
let price = document.createElement("td");
id.textContent = this.id;
name.textContent = this.foodName;
type.textContent = this.foodType;
price.textContent = this.price;
row.appendChild(id);
row.appendChild(name);
row.appendChild(type);
row.appendChild(price);
fTable.appendChild(row);
};
getData();
function getData(){
let retrivedData = localStorage.getItem("stringifiedData");
let parsedData = JSON.parse(retrivedData);
if(parsedData!=null){
for (let i = 0; i < parsedData.length; i++) {
let newFoodOP = new food(
parsedData[i].foodName,
parsedData[i].foodType,
parsedData[i].price
);
}
}
for (let i = 0; i < allFood.length; i++) {
allFood[i].Render();
}
console.log(allFood);
}

Unable to retain the table values after refreshing the browser window

Created a form using html, javascript. After entering the fields, when i click submit button, it saves the user data in localstorage and updates the table rows dynamically. But once i refresh the browser, the table holding the information of all users is lost. I want to retain the table after refreshing the browser.
Click here to view screenshot of page Before refresh
Click here to view screenshot of page After refresh
JS Code :
var testObject = [];
var users = {};
function clear(){
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username,usermail,password,location,organization,gender){
if(username!="" && usermail!="" && password!="" && location!="" && organization!="" && gender!=""){
return true;
}
}
function removeDivChild(str)
{
if(document.getElementById(str).querySelector('p')){
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val,cdiv)
{
if(val=="" && document.getElementById(cdiv).querySelector('p')==null)
{
var node = document.createElement("P");
if(document.getElementById(cdiv).className=="textbox"){
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
}
else if(document.getElementById(cdiv).className=="radiobox"){
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if(val!="" && document.getElementById(cdiv).querySelector('p')!=null)
{
document.getElementById(cdiv).lastElementChild.remove();
}
}
function save(){
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if(document.getElementById("m").checked){
genval = document.getElementById("m").value;
}
if(document.getElementById("f").checked)
{
genval = document.getElementById("f").value;
}
if(IsValid(userval,eval,passval,locval,orgval,genval))
{
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
updateTable();
}
else
{
appendToDiv(userval,"userdiv");
appendToDiv(eval,"maildiv");
appendToDiv(passval,"passdiv");
appendToDiv(locval,"locdiv");
appendToDiv(orgval,"orgdiv");
appendToDiv(genval,"gendiv");
}
}
function updateTable(){
localStorage.setItem("user", JSON.stringify(testObject));
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
if(i==0){
var nodeh = document.createElement("tr");
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
nodeh.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
nodeh.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
nodeh.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
nodeh.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
nodeh.appendChild(onode);
var gnode = document.createElement("th");
var gtext = document.createTextNode("gender");
gnode.appendChild(gtext);
nodeh.appendChild(gnode);
document.getElementById("t").appendChild(nodeh);
}
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
var nodeg = document.createElement("td");
var textg = document.createTextNode(usr[i].gender);
nodeg.appendChild(textg);
noder.appendChild(nodeg);
document.getElementById("t").appendChild(noder);
clear();
}
HTML code :
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="check.js"></script>
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male"/> Male
<input type="radio" name="gender" id="f" value="female"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
After the back and forth in the comments on your question I decided to just create an example from your code sample. Most of it was untouched however I did add comments to the things that I did change.
// I moved the declaration of the testObject below to let the functions be created first
// so i can use teh new loadFromStorage function to create the object
var users = {};
// This is a new function I created
function loadFromStorage() {
// parse the 'user' object in local storage, if its empty return an empty array
return JSON.parse(localStorage.getItem('user')) || [];
}
function clear() {
// I didn't touch this function
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username, usermail, password, location, organization, gender) {
// I didn't touch this function
if (username != "" && usermail != "" && password != "" && location != "" && organization != "" && gender != "") {
return true;
}
}
function removeDivChild(str) {
// I didn't touch this function
if (document.getElementById(str).querySelector('p')) {
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val, cdiv) {
// I didn't touch this function
if (val == "" && document.getElementById(cdiv).querySelector('p') == null) {
var node = document.createElement("P");
if (document.getElementById(cdiv).className == "textbox") {
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
} else if (document.getElementById(cdiv).className == "radiobox") {
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if (val != "" && document.getElementById(cdiv).querySelector('p') != null) {
document.getElementById(cdiv).lastElementChild.remove();
}
}
// Changes in this function
function save() {
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if (document.getElementById("m").checked) {
genval = document.getElementById("m").value;
}
if (document.getElementById("f").checked) {
genval = document.getElementById("f").value;
}
if (IsValid(userval, eval, passval, locval, orgval, genval)) {
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
// Saving testObject to the persistent storage here because this is where it belongs
localStorage.setItem("user", JSON.stringify(testObject));
updateTable();
} else {
appendToDiv(userval, "userdiv");
appendToDiv(eval, "maildiv");
appendToDiv(passval, "passdiv");
appendToDiv(locval, "locdiv");
appendToDiv(orgval, "orgdiv");
appendToDiv(genval, "gendiv");
}
}
// Changes in this function
function updateTable() {
// pulled out the saving and the loading of user from localStorage here,
// everything should already be saved or loaded by the time we call
// this function.
// Also re-wrote this function because it was messy and hard to read, always remember you write code for humans not computers so slightly longer variable names that are descriptive are really good.
// get a reference to the table
var tbl = document.getElementById('t');
// remove all the child rows, except for the header
// CSS Selector explained:
// #t - find the table by the id (you used t)
// > tr > td - find all td's that are direct children of the t table
Array.prototype.forEach.call(document.querySelectorAll('#t > tr > td'), function(node) {
node.parentNode.removeChild( node );
})
// loop over all the 'users' in 'testObject'
for(var i = 0; i < testObject.length; i++){
// store a reference to the current object to make the code easier to read
var currentObject = testObject[i];
// create the TR
var tr = document.createElement('tr');
// Create the td's
var tdUserName = document.createElement('td');
var tdEmail = document.createElement('td');
var tdPassword = document.createElement('td');
var tdLocation = document.createElement('td');
var tdOrganization = document.createElement('td');
var tdGender = document.createElement('td');
// create the text nodes
var userName = document.createTextNode(currentObject.uname);
var email = document.createTextNode(currentObject.email);
var password = document.createTextNode(currentObject.pass);
var location = document.createTextNode(currentObject.loc);
var organization = document.createTextNode(currentObject.org);
var gender = document.createTextNode(currentObject.gender);
// add the elements to their containers
tdUserName.appendChild(userName);
tdEmail.appendChild(email);
tdPassword.appendChild(password);
tdLocation.appendChild(location);
tdOrganization.appendChild(organization);
tdGender.appendChild(gender);
// add the td's to the row
tr.appendChild(tdUserName);
tr.appendChild(tdEmail);
tr.appendChild(tdPassword);
tr.appendChild(tdLocation);
tr.appendChild(tdOrganization);
tr.appendChild(tdGender);
// add the row to the table
tbl.appendChild(tr);
}
// call your clear function
clear();
}
// load the object from storage
var testObject = loadFromStorage();
// populate the table
updateTable();
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male" /> Male
<input type="radio" name="gender" id="f" value="female" /> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<!-- Added the header to the table, it isn't removed now when rebuilding it -->
<table id="t" border="1">
<thead>
<tr>
<td>Username</td>
<td>Email</td>
<td>Password</td>
<td>Location</td>
<td>Organization</td>
<td>Gender</td>
</tr>
</thead>
</table>
Here is a link to a JSFiddle because this example wont run properly because it accesses localStorage but is sandboxed. Working Example

How to add two functions into one, and execute based on parameter passed

Looking to make one button execute two different functions based on the parameters passed in. One function adds a new row to the table based on the filled out form values and the other functions saves the form values in a previously added row. As shown below, I want to add the add the functions
editHtmlTbleSelectedRow() and addHtmlTableRow() into one function and do one or the other based on the parameter passed.
Any help or tips on how to accomplish this would be appreciated, Here is the code:
HTML
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
</table>
</div>
<div class="tab tab-2">>
Name :<input type="text" name="name" id="name" required><p id="errorName" class="hide">*Name: All letters </p>
Email :<input type="email" name="email" id="email" required><p id="errorEmail" class="hide">*Email: blah#blah.com</p>
Age :<input type="number" name="age" id="age" required><p id="errorAge" class="hide">*Age: 3-100 </p>
<button type="button" id="add" class="btn btn-success">Add New</button>
<button type="button" id="edit add" class="btn btn-primary">Save</button>
<button type="button" id="remove" class="btn btn-danger">Remove</button>
</div>
</div>
Javascript
function addHtmlTableRow(){
// get the table by id
// create a new row and cells
// get value from input text
// set the values into row cell's
if(checkEmptyInput()){
resetBorder();
if(document.getElementById('email').value !== "" && document.getElementById('age').value !== "" && document.getElementById('name').value !== ""){
var editBtn = document.createElement('button');
var delBtn = document.createElement('button');
editBtn.innerHTML = 'Edit';
editBtn.id = 'editRow';
delBtn.innerHTML = 'Remove';
delBtn.id = 'removeRow';
var newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell5 = newRow.insertCell(3),
cell4 = newRow.insertCell(4),
name = document.getElementById("name").value,
email = document.getElementById("email").value,
age = document.getElementById("age").value;
cell1.innerHTML = name;
cell2.innerHTML = email;
cell3.innerHTML = age;
cell4.appendChild(delBtn);
cell5.appendChild(editBtn);
document.getElementById("name").value = '';
document.getElementById("email").value= '';
document.getElementById("age").value = '';
// call the function to set the event to the new row
selectedRowToInput();
}
}
}
// display selected row data into input text
function selectedRowToInput()
{
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// get the seected row index
rIndex = this.rowIndex;
document.getElementById("name").value = this.cells[0].innerHTML;
document.getElementById("email").value = this.cells[1].innerHTML;
document.getElementById("age").value = this.cells[2].innerHTML;
};
}
}
selectedRowToInput();
function editHtmlTbleSelectedRow()
{
var name = document.getElementById("name").value,
email = document.getElementById("email").value,
age = document.getElementById("age").value;
console.log(name, email, age);
if(checkEmptyInput()){
table.rows[rIndex].cells[0].innerHTML = name;
table.rows[rIndex].cells[1].innerHTML = email;
table.rows[rIndex].cells[2].innerHTML = age;
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("age").value = "";
console.log(name, email, age);
resetBorder();
}
document.getElementById('add').addEventListener('click',
addHtmlTableRow);
document.getElementById('edit').addEventListener('click',
editHtmlTbleSelectedRow);
Thank you

use input type to print out the date in year-mm-dd

I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>

Javascript: fetch values from textbox of a dynamic datagrid. (skipping some textboxes)

i have seen similar questions to this but none can assist me.as my code is missing some results and i don't now why.
as seen on the image above the output is 6 results instead of 12
This is the code am using to get the values
//Fetch Sales**********************************************
function fetchsales(){
var Dt = document.getElementById("sDate").value;
var Usr = document.getElementById("UserID").value;
var Stp = document.getElementById("tstamp").value;
var e = document.getElementById("sdepot");
var Dpt = e.options[e.selectedIndex].value;
var sale = new Array();
var Tbl = document.getElementById('tbl_sales'); //html table
var tbody = Tbl.tBodies[0]; // Optional, based on what is rendered
for (var i = 2; i < tbody.rows.length; i++) {
var row = tbody.rows[i];
for (var j = 2; j < row.cells.length; j++) {
var cell = row.cells[j];
// For Every Cell get the textbox value
var unitsold = cell.childNodes[0].value ;
//Get selectbox distributor
var Sdist = row.cells[1].childNodes[0]; //Select box always on second coloumn
var Distributor = Sdist.options[Sdist.selectedIndex].value;
//Get selectbox Product
var Sprod = tbody.rows[1].cells[j].childNodes[0];
var Product = Sprod.options[Sprod.selectedIndex].value;
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
}
}
//Debug
var fsale = new Array();
fsale = sale.filter(function(n){return n});
document.getElementById("output").innerHTML = fsale;
}
//End Fetch Sales******************************************************
And this is the Whole Document with the Above code included.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
</style>
<script type="text/javascript">
//*********************************Start Add Row **********************************************************
function addRowToTable() {
var tbl = document.getElementById('tbl_sales'); //html table
var columnCount = tbl.rows[0].cells.length; //no. of columns in table
var rowCount = tbl.rows.length; //no. of rows in table
var row = tbl.insertRow(rowCount); //insert a row method
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0); //Create a new cell
var element_1 = document.createElement("input"); //create a new element
element_1.type = "checkbox"; //set element type
element_1.setAttribute('id', 'newCheckbox'); //set id attribute
cell_1.appendChild(element_1); //Append element to created cell
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('select');
element_2.name = 'SelDist' + rowCount;
element_2.className = 'styled-select';
element_2.options[0] = new Option('John Doe', '1');
element_2.options[1] = new Option('Dane Doe', '2');
cell_2.appendChild(element_2);
// For Every Row Added add a textbox on the rest of the cells starting with the 3rd,4th,5th... coloumns going on...
if (columnCount >= 2) { //Add cells for more than 2 columns
for (var i = 3; i <= columnCount; i++) {
var newCel = row.insertCell(i - 1); //create a new cell
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.className = "rounded";
element_3.name = 'txt_r'+ rowCount +'c'+(i-1);
element_3.id = 'txt_r'+ rowCount +'c'+(i-1);
element_3.size = 5;
element_3.value = 'txt_r'+rowCount+'c'+(i-1);
newCel.appendChild(element_3);
}
}
}
//***************************** End Add Row ***************************************************************
// *****************************Start Add Column**********************************************************
function addColumn() {
var tblBodyObj = document.getElementById('tbl_sales').tBodies[0];
var rowCount = tblBodyObj.rows.length;
//for every Coloumn Added Add checkbox on first row ----------------------------------------------
var newchkbxcell = tblBodyObj.rows[0].insertCell(-1);
var element_4 = document.createElement("input");
element_4.type = "checkbox";
element_4.setAttribute('id', 'newCheckbox');
newchkbxcell.appendChild(element_4);
//For Every Coloumn Added add Drop down list on second row-------------------------------------
var newselectboxcell = tblBodyObj.rows[1].insertCell(-1);
var element_5 = document.createElement('select');
element_5.name = 'SelProd' + rowCount;
element_5.className = 'styled-select';
element_5.options[0] = new Option('Product11', '11');
element_5.options[1] = new Option('Product12', '12');
element_5.options[2] = new Option('Product13', '13');
element_5.options[3] = new Option('Product14', '14');
element_5.options[4] = new Option('Product15', '15');
element_5.options[5] = new Option('Product16', '16');
newselectboxcell.appendChild(element_5);
// For Every Coloumn Added add a textbox on the rest of the row cells starting with the 3rd,4th,5th......
for (var i = 2; i < tblBodyObj.rows.length; i++) { //Add cells in all rows starting with 3rd row
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
var ClmCount = ((tblBodyObj.rows[0].cells.length)-1);
var element_6 = document.createElement("input");
element_6.type = "text";
element_6.className = "rounded"
element_6.name = 'txt_r'+ i + 'c' + ClmCount;
element_6.id = 'txt_r'+ i + 'c' + ClmCount;
element_6.size = 5;
element_6.value = 'txt_r'+i+'c'+ClmCount;
newCell.appendChild(element_6)
}
}
//*****************************Start Delete Selected Rows **************************************************
function deleteSelectedRows() {
var tb = document.getElementById('tbl_sales');
var NoOfrows = tb.rows.length;
for (var i = 0; i < NoOfrows; i++) {
var row = tb.rows[i];
var chkbox = row.cells[0].childNodes[0]; //get check box object
if (null != chkbox && true == chkbox.checked) { //wheather check box is selected
tb.deleteRow(i); //delete the selected row
NoOfrows--; //decrease rowcount by 1
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns() {
var tb = document.getElementById('tbl_sales'); //html table
var NoOfcolumns = tb.rows[0].cells.length; //no. of columns in table
for (var clm = 3; clm < NoOfcolumns; clm++) {
var rw = tb.rows[0]; //0th row with checkboxes
var chkbox = rw.cells[clm].childNodes[0];
console.log('Current Coloumn:'+clm+',', NoOfcolumns, chkbox); // test with Ctrl+Shift+K or F12
if (null != chkbox && true == chkbox.checked) {
//-----------------------------------------------------
var lastrow = tb.rows;
for (var x = 0; x < lastrow.length; x++) {
tb.rows[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
} else {
//alert("not selected");
}
}
}
//*****************************End Delete Selected Columns **************************************************
//Fetch Sales**********************************************
function fetchsales(){
var Dt = document.getElementById("sDate").value;
var Usr = document.getElementById("UserID").value;
var Stp = document.getElementById("tstamp").value;
var e = document.getElementById("sdepot");
var Dpt = e.options[e.selectedIndex].value;
var sale = new Array();
var Tbl = document.getElementById('tbl_sales'); //html table
var tbody = Tbl.tBodies[0]; // Optional, based on what is rendered
for (var i = 2; i < tbody.rows.length; i++) {
var row = tbody.rows[i];
for (var j = 2; j < row.cells.length; j++) {
var cell = row.cells[j];
// For Every Cell get the textbox value
var unitsold = cell.childNodes[0].value ;
//Get selectbox distributor
var Sdist = row.cells[1].childNodes[0]; //Select box always on second coloumn
var Distributor = Sdist.options[Sdist.selectedIndex].value;
//Get selectbox Product
var Sprod = tbody.rows[1].cells[j].childNodes[0];
var Product = Sprod.options[Sprod.selectedIndex].value;
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
}
}
//Debug
var fsale = new Array();
fsale = sale.filter(function(n){return n});
document.getElementById("output").innerHTML = fsale;
}
//End Fetch Sales******************************************************
//on loading create 3 coloumns and 2 rows
window.onload = function () {addColumn();addColumn();addColumn();addRowToTable();addRowToTable();};
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Distributor Sales</title>
</head>
<body>
<!--A--->
<div class="datagrid shadow" style="float:left; min-width:160px; width:220px">
<table id="top">
<tbody>
<tr>
<td width="100px">
<label for="textfield2">Date</label>
<input id="sDate" name="sDate" type="date" size="10" class="rounded" value="2013-06-04" />
</td>
</tr>
<tr class="alt">
<td width="220px">
<label for="select">Depot</label>
<select name="sdepot" id="sdepot" class="styled-select">
<option value="1">Muranga</option>
<option value="2" selected="selected">Nyahururu</option>
<option value="3">Karatina</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
<!--C--->
<div class="datagrid shadow" style="float:left; margin-left:20px; width:250px; min-width:250px">
<table>
<tbody>
<tr>
<td>
<label for="textfield4">User ID</label>
<input id="UserID" name="UserID" type="text" class="rounded" value="121" />
</td>
</tr>
<tr class="alt">
<td>
<label for="textfield5">Time Stamp</label>
<input type="date" name="tstamp" id="tstamp" class="rounded" value="2013-06-02" />
</td>
</tr>
</tbody>
</table>
</div>
<div style="clear:both"></div>
</br>
<div class="mainG gradient-style shadow" style="min-width:500px; min-height:120px">
<table id="tbl_sales" border="1" bordercolor="#E1EEF4" background="table-images/blurry.jpg">
<tr>
<td></td>
<td><input type="button" name="button3" id="button3" value="-Row" onclick="deleteSelectedRows()" />
<input type="button" name="button4" id="button4" value="-Coloumn" onclick="deleteSelectedColoumns()" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" name="addrowbutton" id="adrwbutton" value="+Row" onclick="addRowToTable();" />
<input type="button" name="adclmbutton" id="addclmnbutton" value="+Coloumn" onclick="addColumn()" />
</td>
</tr>
</table>
</div>
<div style="clear:both"></div>
<br/>
<div class="datagrid shadow" style="float:left; margin-left:20px; width:200px; min-width:200px; padding-left:10px">
<table id="bottom1" style="min-width:200px">
<tbody>
<tr>
<td>
<div align="center"><input name="myBtn" type="submit" value="Save Information" onClick="javascript:fetchsales();">
</td>
</tr>
</tbody>
</table>
</div>
<div style="clear:both"></div>
<br/>
<div id="output"></div>
</body>
</html>
NB: am hoping to concatenate the result to a mysql insert statement
Any assistance will be greatly appreciated.
The problem comes from this line:
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
using the for loops indexes multiplied by themselves doesnt ensure unique array indexes, in some cases they are repeated (like for example 2*3 and 3*2) and the previous value in the array gets overwritten.

Categories

Resources