I have a table with inputs in the cells. These inputs need to be inserted into SQL in a single insert. I am having trouble with just trying to build the arrays. I can push the value that is inputted into an array no problem. Its when I push another input, the first array is overwritten. I need the array to resume or a new one to be created so the contents of the first array are stored and the values for the second array of data are stored all in one array.
I want the user to click a save button which takes all that data and inserts it into sql. There may be only 1 array of data or 3 arrays or 10 arrays. So I guess the question becomes; How do I create an array and push values inside a global array then create another array and push values in the global array without clearing the first array's values?
I haven't gotten to the AJAX request yet, just trying to build the array in preparation.
Any help is most appreciated.
HTML
<tr class="rows" id="row3" >
<td class="celltimes4a"id="row3Project"></td>
<td class="celltimes4c"id="row3Name">General</td>
<td class="celltimes4"id="row3Sun" ><input id="num3Sun" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Mon" ><input id="num3Mon" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Tue" ><input id="num3Tue" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Wed" ><input id="num3Wed" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Thu" ><input id="num3Thu" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Fri" ><input id="num3Fri" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Sat" ><input id="num3Sat" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4b"id="total3"></td>
</tr>
JavaScript
var temp = {};
var SqlArr = [];
function tott(element) {
var totwLeg = element.id;
var splitNumero = totwLeg.split(/([A-Za-z]+)([0-9]+)/);
var getNumero = splitNumero[2];
var getDay = splitNumero[3];
var EmpId = document.getElementById('num1').value;
var WeekEnding = document.getElementById('theDate').value;
var DateOccur = document.getElementById('row1' + getDay).innerHTML;
var JobNum = getNumero - 2;
var Customer = getNumero - 2;
var HourValue = document.getElementById('num' + getNumero + getDay).value;
var cnt = 0;
Empdata = 'EmpData' + cnt + '';
temp = {
EmpId, WeekEnding, DateOccur, JobNum, Customer, HourValue
};
SqlArr.push({
Empdata: temp
});
}
Results
temp=EmpId="2", WeekEnding="09-19-2015",DateOccur="09-14-2015",JobNum=6,Customer=6,HourValue="2"
Desired Results
temp={EmpId="2", WeekEnding="09-19-2015",DateOccur="09-14-2015",JobNum=6,Customer=6,HourValue="2"},{EmpId="2", WeekEnding="09-19-2015",DateOccur="09-16-2015",JobNum=6,Customer=6,HourValue="4"},{EmpId="2", WeekEnding="09-19-2015",DateOccur="09-16-2015",JobNum=6,Customer=6,HourValue="5"}
Not sure this is all that's wrong but first take var SqlArr = []; out of your function tott(). Every time you call the function you create a new empty array. So when you call SqlArr.push() your always pushing the first item on the array.
OK it looks like it's working to me. Check out this fiddle: http://jsfiddle.net/r1L9oj80/1/
However you might look at your 'DateOccur' variable. it contains your entire input element.
Your temp object is invalid, try it like this...
temp = {
'EmpId': EmpId, 'WeekEnding': WeekEnding, 'DateOccur': DateOccur, 'JobNum': JobNum, 'Customer': Customer, 'HourValue': HourValue
};
plus the array SqlArr should be defined outside the function as mentioned in another answer...
Related
I used for loop to copy the table to n times. The code below works only in first table. How can i get to work in all tables?. I am a beginner.
function copy() {
var text1 = document.getElementById("Name1").value;
document.getElementById("Name2").value = text1;
var text2 = document.getElementById("Name3").value;
document.getElementById("Name4").value = text2;
}
<td rowspan="3" style="height:100px;">Name <input type="text" name="Emp name" placeholder="enter your name" id="Name1" /><br> ID <input type="id" name="Emp Id" placeholder="enter id" id="Name3"> </td>
<tr id="p001">
<td colspan="10" style="border:1px solid #ffffff;height:150px;"><input type="button" value="Get data" onclick="copy();" /><label for="text"> Name : <input type="text" id="Name2"></label>
<label for="text"> ID : <input type="id" id="Name4"></label> </td>
</tr>
ID's should always be unique. When using duplicate ID's it will only work on the first one and ignore the rest. By pushing in the selector to the function you can reuse your function for multiple tables.
https://jsfiddle.net/m5aqdswe/
onclick="copy('Name');"
function copy(selector) {
var text1 = document.getElementById(selector + "1").value;
document.getElementById(selector + "2").value = text1;
var text2 = document.getElementById(selector + "3").value;
document.getElementById(selector + "4").value = text2;
}
Hope this helps
EDIT TO HELP WITH YOUR FIDDLE MISTAKE
After checking your code I can see that you haven't implemented my fix. You have an onclick on the button calling copy();. You're not passing in any arguments so your JS is static. So when you add another table you're creating duplicate ID's.
When searching for an ID document.getElementById("Name1") it will search through the DOM until it finds that first id="Name1" and then stop. That is why your second table never works.
To fix that we need to push in your ID name to the function so that the JS becomes dynamic. copy('Name') where "Name" is the first part of your ID. The numbers will still be used.
In the function you need to grab that arguments by passing it in to the function and calling it whatever you like. I chose 'selector' because it is most descriptive. onclick="copy(selector)"
No the function will replace all the 'selector' variables with the string you passed through, namely "Name" so document.getElementById(selector + "1") will actually be document.getElementById("Name1"). This way you can create as many clones as you like but remember to change the clone table ID's and pass in the correct argument to the onclick.
Here is your fixed fiddle. https://jsfiddle.net/3shjhu98/2/
Please don't just copy, go see what I did. You'll need to fix your clone function to use dynamic arguments instead of static ones.
function check() {
var rowCount = $('table.mytable tbody tr');
for (var index = 0; index < rowCount.length; index++) {
var tr = $('table.mytable tbody tr')[index];
var td = $(tr).find('td');
for (var j = 0; j < rowCount.length; j++) {
copy('table.mytable tbody tr[data-index=' + index + '] td[data-index=' + j + ']');
}
}
}
function copy(selector) {
var val_1 = $(selector).find('input:first').val();
$(selector).find('input:last').val(val_1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="mytable">
<tbody>
<tr data-index="0">
<td data-index="0">
<input type="text" onblur="check()" />
<input type="text" />
</td>
</tr>
</tbody>
</table>
Hi. try it...
I think you need to pass table selector like [ table.className ] etc. then you find input text box and get the value this and paste into another text box.
Like this.
///it mean you pass first table row of first table data.
copy('table.className tbody tr[data-index=1] td[data-index=1]');
function copy(selector) {
var val_1 = $(selector).find('input#Name1').val();
$(selector).find('input#Name2').val(val_1);
}
I have an array in JavaScript that has multiple objects. Inside the object has multiple elements. I am trying to insert those elements in PHP using AJAX and into SQL.
I can pass the array into PHP fine, but when I encode the array and echo the data back, I have a bunch of strings. I just need to break down those elements and insert them into SQL.
How do I get the php similar to my 'desired results' posted at the bottom so that I can insert multiple rows of data into SQL in one query with the data 'SqlArr'
Any help is most appreciated.
HTML
<tr class="rows" id="row3" >
<td class="celltimes4a"id="row3Project"></td>
<td class="celltimes4c"id="row3Name">General</td>
<td class="celltimes4"id="row3Sun" ><input id="num3Sun" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Mon" ><input id="num3Mon" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Tue" ><input id="num3Tue" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Wed" ><input id="num3Wed" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Thu" ><input id="num3Thu" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Fri" ><input id="num3Fri" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4"id="row3Sat" ><input id="num3Sat" class="alignRight" type="text" name="hours" value="" onchange="tott(this)"></input></td>
<td class="celltimes4b"id="total3"></td>
</tr>
Javascript
function tott(element) {
var totwLeg = element.id;
var splitNumero = totwLeg.split(/([A-Za-z]+)([0-9]+)/);
var getNumero = splitNumero[2];
var getDay = splitNumero[3];
EmpId = document.getElementById('num1').value;
WkEnd = document.getElementById('theDate').value;
Day = document.getElementById('row1' + getDay).innerHTML;
Title = getNumero - 2;
Description = getNumero - 2;
Value = document.getElementById('num' + getNumero + getDay).value;
AbbrevJob = Title;
//Empdata = 'EmpData' + cnt + '';
temp = {
EmpId, WkEnd, Day, Title, Description, Value, AbbrevJob
}; // this is where the columsn should match or go inside the columsn in the table... hold one moment
SqlArr.push(temp);
//JSON.stringify(SqlArr);
}
function saveMe() {
$.post('php/GetEmployeeData.php', {
'SqlArr': SqlArr,
datatype: "json"
}, function(SqlArr) {
alert(SqlArr);
})
}
PHP
<?php
include_once 'DbConnectPSI.php';
global $connect;
global $record3;
global $myData3;
$SqlArr =$_POST['SqlArr'];
$SqlArr =json_encode($_POST['SqlArr']);
//$SqlArr =json_decode($SqlArr);
//$SqlArr=implode(',',$SqlArr);
//$SqlArr=explode(',',$SqlArr);
//$SqlArr=$SqlArr[0];
//$myData3="Insert Into EmployeeTimesheets(EmpId, WkEnd, Day, Title, Description, Value,TimeStamp, AbbrevJob) Values('$SqlArr[0][EmpId]','$SqlArr[0][WkEnd]','$SqlArr[0][Day]','$SqlArr[0][Title]','$SqlArr[0][Description]','$SqlArr[0][Value]', getDate(),'$SqlArr[0][AbbrevJob]')"; // this is my sql statment that is supposed to be inserting the data into the table.
//$myData3="Insert Into EmployeeTimesheets Values('$var1','$var2','$var3','$var4','$var5','$var6', getDate())";
//$myData3="Insert Into EmployeeTimesheets Values('$EmpId','$WkEnd','$Day','$Title','$Description','$Value', getDate(),'$AbbrevJob')";
//$record3 = odbc_exec($connect, $myData3);
echo($SqlArr);
odbc_close($connect);
?>
alert of data
Desired results so the values can be inserted into SQL
Array ( [0] => 7 [1] => 09-19-2015 [2] => 09-13-2015 [3] => 1 [4] => 1 [5] => 7 [6]=>1 )
Array ( [0] => 7 [1] => 09-19-2015 [2] => 09-13-2015 [3] => 2 [4] => 2 [5] => 4 [6]=>2 )
I'm trying to do mi own serialize function (like in jQuery), I need to get inputs and selects in an array in order to serialize it.
The problem is that methods "push" and "pop" doesn't exist in DOM elements arrays (Error: "Undefined is not a function").
HTML:
<form>
<table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td><label for="age">Age:</label></td>
<td><input type="number" id="age" name="age"/></td>
</tr>
<tr>
<td><label for="genre">Genre:</label></td>
<td><select name="genre" id="genre">
<option>Female</option>
<option>Male</option>
</select></td>
</tr>
</table>
</form>
Javascript:
HTMLFormElement.prototype.ownSerialize=function() {
var inputs = this.getElementsByTagName('input');
var selects = this.getElementsByTagName('select');
while(selects.length)inputs.push(selects.pop());//Breaks here
console.log(inputs);
var json = {};
for (var f=0; f<inputs.length; f++) {
json[inputs[f].id]=inputs[f].value;
}
console.log(json);
var str = "?";
for(f in json){
str+=f+"="+json[f]+"&"
}
str = str.slice(0,-1); //Delete de last "&"
console.log(str);
};
document.getElementsByTagName('form')[0].ownSerialize();
How can I achieve it?
http://jsfiddle.net/mpecdv2t/
(Hope my english is correct)
You can convert HTMLCollection (and any other array-like collection) to native array with Array.prototype.slice method:
var slice = Array.prototype.slice;
var inputs = slice.call(this.getElementsByTagName('input'));
var selects = slice.call(this.getElementsByTagName('select'));
After that inputs and selects are true javascript arrays with DOM elements as array elements.
Demo: http://jsfiddle.net/mpecdv2t/1/
I have this code in a function:
tableFields = tableFields.children;
for (item in tableFields) {
// Do stuff
}
According to a console.log of tableFields, I am getting an array back as I assume I need to do. A console.log of item within the loops returns undefined. What do I have to do to loop through tableFields and insert each object into a table?
console log of tableFields:
HTMLCollection[label, input, label, input 25, label, input, input, input Remove]
0
label
1
input
2
label
3
input 25
4
label
5
input
6
input
7
input Remove
description[]
input
hours[]
input
invoice_number
input
getlength
8
rate[]
input 25
item
item()
iterator
iterator()
namedItem
namedItem()
__proto__
HTMLCollectionPrototype { item=item(), namedItem=namedItem(), iterator=iterator()}
Here is the entire section of code as I have so far:
$this->title("Test");
$this->defaultMenu();
$select = "";
$names = Customer::getNames();
foreach ($names as $id => $name) {
$select .= '<option value="'.$id.'"';
if ($this->customerid == $id) $select .= ' selected ';
$select .= '>'.$name.'</option>';
}
$form = '
<script type="text/javascript">
var counter = 0;
function isEven(int){
int = Number(int);
return (int%2 == 0);
}
function moreLabor() {
var table = document.getElementById("editTable");
var tableFields = document.getElementById("readroot");
tableFields = tableFields.children;
console.log(tableFields);
for (item in tableFields) {
if (isEven(counter)) {
var tableRow = table.insertRow(-1);
var label = tableRow.insertCell(-1);
console.log(tableFields[item]);
label.appendChild(tableFields[item]);
} else {
var field = tableRow.insertCell(-1);
field.innerHTML = item.innerHTML;
}
counter++;
}
console.log();
var insertHere = document.getElementById("writeroot");
}
window.onload = function(){
document.getElementById(\'moreLabor\').onclick = function(){ moreLabor(); }
moreLabor();
}
</script>
<div id="readroot" style="display: none">
<tr>
<td><label for="hours">Hours:</label></td>
<td><input type="text" name="hours[]" value="" /></td>
</tr>
<tr>
<td><label for="rate">Rate:</label></td>
<td><input type="text" name="rate[]" value="25" /></td>
</tr>
<tr>
<td><label for="description">Description:</label></td>
<td><input type="text" name="description[]" value="" /></td>
</tr>
<input type="hidden" name="invoice_number" value="'.$this->number.'" />
<tr>
<td><input type="button" value="Remove"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /></td>
</tr>
</div>
<form method="POST" class="invoice" id="edit">
<table id="editTable">
<tr>
<td><label>Work Order Number:</label></td>
<td><input type="text" name="number" value="'.$this->number.'"/></td>
</tr>
<tr>
<td><label>Customer:</label></td>
<td><select name="customerid">'.$select.'</select></td>
</tr>
<span id="writeroot"></span>
<tr>
<td><input type="button" id="moreLabor" value="Add labor"/></td>
<td><input type="submit" name="Save" value="Save" /></td>
</tr>';
if (!is_null($this->id)) {
$form .= '<input type="hidden" name="id" value="'.$this->id.'"/>';
}
$form .= '</table></form>';
$this->component($form);
The trick is that the DOM Element.children attribute is not an array but an array-like collection which has length and can be indexed like an array, but it is not an array:
var children = tableFields.children;
for (var i = 0; i < children.length; i++) {
var tableChild = children[i];
// Do stuff
}
Incidentally, in general it is a better practice to iterate over an array using a basic for-loop instead of a for-in-loop.
In ECS6, one may use Array.from() or Spread array syntax:
const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
// or
const listArray = [...listItems];
listArray.forEach((item) => {console.log(item)});
if tableFields is an array , you can loop through elements as following :
for (item in tableFields); {
console.log(tableFields[item]);
}
by the way i saw a logical error in you'r code.just remove ; from end of for loop
right here :
for (item in tableFields); { .
this will cause you'r loop to do just nothing.and the following line will be executed only once :
// Do stuff
Modern JS also uses the for..of to enable us to iterate DOM children objects, array, or other iterable objects. I think it is very clean and simple.
var children = tableFields.children;
for (c of children) {
console.log(c);
// Do stuff with child c
}
The backwards compatible version (IE9+) is
var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
// Do stuff
});
The es6 way is
const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
// Do stuff
});
Using ES6,
[...element.children].map(child => console.log(child));
In the year 2020 / 2021 it is even easier with Array.from to 'convert' from a array-like nodes to an actual array, and then using .map to loop through the resulting array.
The code is as simple as the follows:
Array.from(tableFields.children).map((child)=>console.log(child))
I’m surprised no-one answered with this code:
for(var child=elt.firstChild;
child;
child=child.nextSibling){
do_thing(child);
}
Or, if you only want children which are elements,
this code:
for(var child=elt.firstElementChild;
child;
child=child.nextElementSibling){
do_thing(child);
}
i want to iterate through the table rows and get the id and name of each checkbox checked in each tr in the first td and save it in a new Object() called values ex: values.id, values.name
Thanks
<table>
<tr>
<td>
<input id="1" type="checkbox" name="name1" checked="checked">
</td>
<td>
Some input control 1
</td>
</tr>
<tr>
<td>
<input id="2" type="checkbox" name="name2">
</td>
<td>
Some input control 2
</td>
</tr>
</table>
Working example
aRecord is an array of objects with each object containing both the name and ID of each checked checkbox found in the table.
$(document).ready(function() {
var aRecord = [];
$('#your_table input:checkbox:checked').each(function() {
var oChkBox = {};
oChkBox.name = $(this).attr('name');
oChkBox.id = $(this).attr('id');
aRecord.push(oChkBox);
});
var i = aRecord.length;
while (i--) {
alert("Name: "+ aRecord[i].name + " ID: "+ aRecord[i].id);
}
});
http://jsfiddle.net/tracyfu/r6RMV/
var values = {};
$('tr input:checked').each(function(i) {
values[i] = [];
values[i].push($(this).attr('id'));
values[i].push($(this).attr('name'));
});
Will produce:
values = { [1, 'name1'] }
I'm leaving this solution as-is, since you specifically said you wanted to store the values in an object named values, but without knowing what you're going to do with the data, I would store the values in an array instead...