How to send a table html as a serialize array to database? - javascript

I want to send my javascript and dynamic table to my database as a text variable.
I explained whatever I did:
I used jquery to get the values
Then I stored HTML table values in a java script array
I converted javascript array to JSON format
I sent JSON array to a php script by JQuery AJAX
But, I don’t know how to send it to database?
Here is my code:
function readTblValues() {
var TableData = '';
$('#tbTableValues').val(''); // clear textbox
$('#tblDowntimes tr').each(function(row, tr) {
TableData = TableData +
$(tr).find('td:eq(1)').text() + ' ' // downtime
+
$(tr).find('td:eq(2)').text() + ' ' // equipment
+
$(tr).find('td:eq(3)').text() + ' ' // starttime
+
$(tr).find('td:eq(4)').text() + ' ' // finishtime
+
$(tr).find('td:eq(5)').text() + ' ' // descriptio
+
'\n';
});
$('#tbTableValues').html(TableData);
}
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').html('<br>JS Array: <br>' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#tblDowntimes tr').each(function(row, tr) {
TableData[row] = {
"DOWNTIME": $(tr).find('td:eq(1)').text(),
"equipment": $(tr).find('td:eq(2)').text(),
"startdowntime": $(tr).find('td:eq(3)').text(),
"finishdowntime": $(tr).find('td:eq(4)').text(),
"description": $(tr).find('td:eq(5)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').html('<br>JSON array: <br>' + TableData.replace(/},/g, "},<br>"));
}
function sendTblDataToServer() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbSendTblDataToServer').val('JSON array to send to server: <br<br>' + TableData.replace(/},/g, "},<br>"));
$.ajax({
type: "POST",
url: "test.php",
data: "pTableData=" + TableData, // post TableData to server script
success: function(msg) {
// return value stored in msg variable
$('#tbServerResponse').html('Server Response:<br><br><pre>' + msg + '</pre>');
}
});
}
function print_r(arr, level) {
var dumped_text = "";
if (!level)
level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++)
level_padding += " ";
if (typeof(arr) === 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof(value) === 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
}
return dumped_text;
}
<html>
<head>
</head>
<body>
<form name="data-entry" method="post" action="data-entry.php">
<input id="product-name" name="product-name" />
<input id="product-quantity" name="product-quantity" />
<input name="Downtime" id="Downtime" />
<input name="equipment" id="equipment" />
<input type='time' name='startdowntime' id='startdowntime' />
<input type='time' name='finishdowntime' id='finishdowntime' />
<input type='text' name='description' id='description' />
<input type="button" value="add rows" id="btnAdd" onclick="addDowntime(this)" />
<input type="button" value="remove rows" onclick="deleteSelected()" />
<table id="tblDowntimes" class="downtime">
<tr>
<th><input type="checkbox" id="chkAll" onclick="chkAll_click(this)" /></th>
<th>downtime</th>
<th>equipment</th>
<th>start-time</th>
<th>finih-time</th>
<th>description</th>
</tr>
</table>
<input type="button" value="1. Read Table Values" name="read" onClick="readTblValues()" />
<input type="button" value="2. Store values in JS Array" name="store" onClick="storeAndShowTableValues()" />
<input type="button" value="3. Convert JS Array to json" name="convert" onClick="convertArrayToJSON()" />
<input type="button" value="4. Send json array to Server" name="send" onClick="sendTblDataToServer()" />
<div id="tbTableValues"></div>
<div id="tbTableValuesArray"></div>
<div id="tbConvertToJSON"></div>
<div id="tbServerResponse"></div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
and Here is my php code:
function processJSONArray() {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData);
var_dump($tableData);
}
echo processJSONArray();
With aforementioned code, I manage to get the array in client side, but when I use this code that error is appeared (Undefined variable: tableData)
if(isset($_POST[‘submit’])){
echo $tableData;
}

Related

Generate a multidimensional array for php post, using data attributes of inputs

I have set a code to generate dynamic tables to capture data, which will be used to send a message to the students regarding a timetable. Following generates the required user input form, so that the user can insert the data as required.
$(document).ready(function() {
var index = 1;
var tableindex = 0;
var daydd = '<select><option value="Saturday">Saturday</option><option value="Sunday">Sunday</option></select>';
$("#addRow").click(function() {
if (tableindex == 0) {
tableindex++;
$("#myTable").append("<tr data-day='" + tableindex + "'><td colspan=3>"+daydd+" " + tableindex + "</td><td><button class='dayclose' data-day='" + tableindex + "'>Close</button></td></tr>");
}
$("#myTable").append("<tr data-day='" + tableindex + "'><td>Day " + tableindex + "</td><td>row " + index + "</td><td><input type='text' data-clday='" + tableindex + "' data-subj='" + index + "' ></td><td><button class='subjclose' id='" + index + "'>Close</button></td></tr>");
index++;
});
$("#addtable").click(function() {
tableindex++;
$("#myTable").append("<tr data-day='" + tableindex + "'><td colspan=3>"+daydd+" " + tableindex + "</td><td><button class='dayclose' data-day='" + tableindex + "'>Close</button></td></tr><tr data-day='" + tableindex + "'><td>Day " + tableindex + "</td><td>row " + index + "</td><td><input type='text' data-clday='" + tableindex + "' data-subj='" + index + "' ></td><td><button class='subjclose' id='" + tableindex + "'>Close</button></td></tr>");
index++;
});
$('table').on('click', '.subjclose', function(e) {
e.preventDefault();
$(this).parents('tr').remove();
});
$('table').on('click', '.dayclose', function(e) {
e.preventDefault();
var closeday = $(this).attr("data-day");
$('tr[data-day="' + closeday + '"]').remove();
$(this).parents('tr').remove();
});
//$('.row-container[data="product_id"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="myTable">
</table>
<input type="button" id="addRow" value="add subject" />
<input type="button" id="addtable" value="add day" />
<input type="button" id="submit" value="Send Data" />
Now I am trying to capture data to be sent to a php script, so that it can send the message to a selected set of students. My message would be as follows; (consider rows 3,4,6,9 as deleted in this scenario)
Saturday Subjects
Row 1 data
Row 2 data
Sunday Subjects
Row 5 data
Row 7 data
Monday Subjects
Row 8 data
Row 10 data
I am trying to run a for each loop for this in my php script, but I do not have any idea how to achieve this with the data attributes.
How can I generate a multidimensional array to be sent to a php script using the data attributes of inputs so that it can be used to generate a foreach loop?
You can use the JQuery function like this
$.fn.onAddDefaultValue = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
data: '',
profile_main_div_id: '',
server_div_id: '',
addi_id : '',
confirm_btn_id: ''
}, options);
$(settings.data).each(function(idx,obj){
var item_id = obj.item_id;
var item_title = obj.item_title;
// server pratik - 10112017 location widget interaction
var isLocationExist = false;
$("#"+settings.server_div_id).children().each(function () {
var child_div = $(this);
var localtion_value = child_div.find("span").text();
if (localtion_value == item_title) {
//child_div.find("span").css("border", "1px solid #f16262");
isLocationExist = true;
//return false;
}else {
//child_div.find("span").css("border", "0px solid #f16262");
}
});
if (!isLocationExist) {
var input_value = item_title;
var newTextBoxDiv = $(document.createElement('div'))
.attr({"class": 'customcheckbox',"style":'margin: 0px 0px 10px;'});
var chk_id = item_id;
newTextBoxDiv.after().html('<input type="checkbox" checked name="remember" id="'+chk_id+'" value="user_profile_remember_me-no">'+
'<input type="hidden" class="server_item_id" value="'+item_id+'" />'+
'<label style="float: right;position: relative;margin-right: 10px;border: 1px solid #000000;border-radius: 0px" for="'+chk_id+'">'+
'<div class="input-label"></div>'+
'</label>'+
'<span style="padding-left: 5px;" class="my-label1">'+input_value+'</span>');
newTextBoxDiv.appendTo("#"+settings.server_div_id);
//$("#"+settings.addi_id).slideUp();
//$(this).closest('#'+settings.profile_main_div_id).removeClass("additional-field-open");
// add new item
} else {
$('#'+settings.server_div_id).children().each(function () {
var child_div_appearance = $(this);
var title_v = $(this).find("span").text();
var status_v = $(this).find("input[type='checkbox']").prop("checked");
if((item_title == title_v) && (!status_v)){
$(this).find("input[type='checkbox']").click();//attr("checked",false)
// break loop
// return false;
}
});
}
$("#"+settings.confirm_btn_id).click();
//$("#"+settings.server_div_id).addClientNote({});
});
};
and remove added element like this
$.fn.removeDiagnosisValue = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
title: ''
}, options);
$(this).children().each(function () {
var child_div = $(this);
var div_buttons = child_div.find("div");
var i = 0;
$(div_buttons).children().each(function () {
// delete icon
var child_span = $(this);
if (child_span.attr('name') == "delete") {
var img_delete = child_span.find("img");
img_delete.click(function () {
child_div.remove();
});
// break loop
return false;
}
});
});
};

How can I set up a button handler to remove a parent table row?

I have this HTML & jQuery project, and everything currently works perfectly for what I want them to do. What I need right now is to add a Delete/Remove Button that is linked to this line:
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
As you can see the buttons are visible only if you click the add button and create a new TR with values.
I tried creating a jQuery function:
function removeThis(a) {
$('tr-' + 'a').remove();
}
But of course, it's not doing what I need it to do.
Can anyone help me resolving this?
Thanks in advance.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
$('tr-' + 'a').remove();
}
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >
I don't want any of the other functions to be deleted.
BTW the Delete button is already added with ID removeThis.
Thank you very much in advance.
You can achieve this without jQuery at all, and I highly recommend that.
function removeThis(e){
const parentTd = e.parentNode;
const parentTr = parentTd.parentNode;
const parentTable = parentTr.parentNode;
return parentTable.removeChild(parentTr);
}
And on your button you do
<button onClick='removeThis(this)'>Delete me</button>
This way you create a testable and reusable function that you can use to remove all DOM Elements.
Oh, and by the way, this way you work from inside-out rather than querying the whole document for the element intended to remove.
Your example function below builds a string 'tr-' + 'a' which will always just look for "tr-a":
function removeThis(a) {
$('tr-' + 'a').remove();
}
Just remove the quotes from around 'a':
function removeThis(a) {
$('tr-' + a).remove();
}
Remove the quotes around the letter 'a' so you can use the variable there:
function removeThis(a) {
$('.tr-' + a).remove();
}
You should also consider using a different way to number the table rows. The row numbers will start to get reused if you delete a row and then add a new one:
Row 0, Row 1, Row 2, Row 3, Row 4
Add row. There are 5 rows, so the new row is row 5.
Row 0, Row 1, Row 2, Row 3, Row 4, Row 5
Remove row 1.
Row 0, Row 2, Row 3, Row 4, Row 5
Add row. There are 5 (!!!) rows, so the new row is (also!!!) row 5.
Row 0, Row 2, Row 3, Row 4, Row 5, Row 5
Instead of getting a new value for tr every time you add a row, instead consider a global variable that you increment every time you add a row:
var rowCounter = 0;
function addNewTr() {
//snip
rowCounter++;
$('table tbody').append('' +
'<tr class="tr-' + rowCounter + '">' +
//snip
}
I think you just need to remove the quotes from 'a':
function removeThis(a) {
$('.tr-' + a).remove();
}
EDIT: This snippet is totally working! I did need to add a dot before 'tr' since it is a class.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
alert('.tr-'+a);
$('.tr-' + a).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >

I want to remove an array item when generated check box checked

I made a todolist which is taking value from input and add an item from array so when the given value shown in page i want to remove an item form array whn checkbox checked.
Html part :
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
javascript part:
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><input id='box' onClick='remove()' type='checkbox' /><label>" + data[i] + "</label></div>";
}
}
function remove() {
var check = document.getElementById('box').value;
for ( var i in list) {
if (list[i]!= check) {
}
}
}
Try this with pure javascript :
Array.splice and Array.indexof()
Add with checkbox inside the label tag.
And click event change with remove(this).Then easly find the label
text and match with list array.
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
}
function remove(that) {
var check = that.parentElement.textContent;
//that.remove() if you need remove clicked box
for ( var i in list) {
if (list[i] == check) {
list.splice(list.indexOf(check),1);
}
}
console.log(list)
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div id='remove" + i + "'><label for='box" + i + "'><input id='box" + i + "' onClick='remove(" + i + ")' type='checkbox' />" + data[i] + "</label></div>";
}
}
function remove(targetId) {
var check = document.getElementById('box' + targetId).checked;
if(check){
console.log('Remove box' + targetId);
document.getElementById('remove' + targetId).innerHTML='';
}
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
I just modified your JavaScript to pass an ID with a number to set each label apart from each other..

userHow to collect the values from html form for variable input values in google app script?

I am creating the input fields with the add more feature which are then sent to the google script file, how can I collect the values of the fields as shown in code I implemented below..
google app script file
code.gs
function getFormValue(formValue) {
var myarr= {};
var count = formValue.count;
for(var g = 1; g<=count; g++ )
{
user["I"+g] = formValue.user+g; // error, what to do here
}
// code
}
index.html
<script>
$(document).ready(function() {
var counter = 2;
$("#addMoreUser").click(function() {
if (counter > 7) {
alert("Only 7 Users are allowed");
return false;
}
var newRowDiv = $(document.createElement('div'))
.attr("id", 'rowDiv' + counter);
newRowDiv.after().html('<div class="row" id="rowDiv" ><div class="col-md-3"><input class="form-control" placeholder="user'+ counter +' " name="user'+ counter +'" id="user'+ counter +'" type="text" value=""></div></div>');
newRowDiv.appendTo("#rowDivGroup");
$("#count").val(counter);
counter++;
});
$( "#submitForm" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
console.log(ret);
}).getFormValue(this); //"this" is the form element
});
});
</script
<form class="contact-form" id="myform">
<input type="hidden" value="1" name="count" id="count">
<div id="rowDivGroup">
<div class="row" id="rowDiv">
<div class="col-md-3">
<input class="form-control" placeholder="Name of User" name="user1" id="user1" type="text" value=""></div></div></div>
<a class="btn btn-sm btn-flat btn-success btn-rounded" id="addMoreUser">Add More Users</a>
<input type="submit" class="btn btn-flat flat-color btn-rounded btn-sm" id="submitForm" value="Submit Details ">
</form>
This code takes the value of an array, and creates an object:
function getFormValue(formValue) {
formValue = ["someInput1", "someInput2", "someInput3", "someInput4", "someInput5", "someInput6", "someInput7"];
Logger.log('formValue: ' + formValue);
var myarr= {};
var count = formValue.length;
Logger.log('count: ' + count);
var user = {};
for(var g = 1; g<=count; g++ )
{
Logger.log('g: ' + g);
var k = "user"+g;
var userID = "I" + g;
Logger.log("userID: " + userID);
Logger.log("formValue: " + formValue[g-1]);
user[userID] = formValue[g-1];
Logger.log("The property value: " + user[userID]);
}
}
I've run the code, and it works. The values for the array are hard coded for testing purposes.

How to retrive the values from html and print it using javascript

This is my html code I want a javascript to get the values from the text box and print it on the same page
<body>
<header>
<h1>Welcome!</h1>
</header>
<form name="myform" method="post" action="#"><table align="center"><tr>
<td>First Name</td>
<td><input type="text" name="fn" id="fn" required="required"/></td></tr><tr>
<td>last Name</td>
<td><input type="text" name="ln" id="ln" required="required"/></td></tr><tr>
<td>DOB</td>
<td><input type="text" name="dob" id="dob" required="required"/></td></tr><tr>
<td>Description</td>
<td><textarea name="fn" cols="16" rows="5" id="txt" required="required"></textarea></td></tr><tr>
<td><input type="button" value="submit" onclick="validate()" /></td>
</tr>
</table>
</form>
</body>
</html>
I tired to print it in the table form using the javascript displayed below .. It is not working can u suggest some other code
val = ''
val += 'First Name: '.append("<tr><td>" + document.getElementById('fn').value + "</td></tr></br>");
val += 'Last Name: ' .append("<tr><td>" +document.getElementById('ln').value + "</td></tr></br>");
+ '<br>';
val += 'DOB: ' + document.getElementById('dob').value + '<br>';
val += 'Description: ' + document.getElementById('txt').value + '<br>';
divprint = document.createElement('div')
divprint.innerHTML = val; document.body.appendChild(divprint)
// grab a reference to the HTML input element
var elem = document.getElementById('fn');
// Retrieve its value (contained text)
var fnValue = elem.value;
// Print on the page
document.write(fnValue)
UPDATE
For other fields is similar to the above code:
var elemLn = document.getElementById('ln');
var LnValue = elemLn.value;
document.write('<br/>' + LnValue);
var elemDob = document.getElementById('dob');
var DobValue = elemDob.value;
document.write('<br/>' + DobValue);
try this ...
Create a div and append it into Body and place the Values in that div..
function validate() {
val = ''
val += document.getElementById('fn').value +'<br>';
val += document.getElementById('ln').value +'<br>';
val += document.getElementById('dob').value +'<br>';
val += document.getElementById('txt').value +'<br>';
divprint = document.createElement('div')
divprint.innerHTML = val;
document.body.appendChild(divprint)
}
USe this for table format
val = ''
val = "<tr><td>first Name: " + document.getElementById('fn').value +'</td></tr>';
val += "<tr><td>Last Name: " +document.getElementById('ln').value +'</td></tr>';
val += "<tr><td>DOB: " +document.getElementById('dob').value +'</td></tr>';
val += "<tr><td>Description: " +document.getElementById('txt').value +'</td></tr>';
divprint = document.createElement('table')
divprint.innerHTML = val;
// divprint.style.border = '1px solid black';
divprint.border = '1';
document.body.appendChild(divprint)
You can use this script before the </body> tag
<script>
function validate() {
return document.getElementById('txt').value;
// or do something with the value...
}
</script>
Add this right after </form>
<div id="emptyDiv"></div>
<script type="text/javascript">
function validate(){
document.getElementById("emptyDiv").innerText = document.getElementById("txt").value;
}
</script>
or the function can have:
document.getElementById("emptyDiv").innerText = document.myform.fn.value;

Categories

Resources