Read json and create table javascript - javascript

I am am trying to read json data and import it to my table in html.
But some how it is not working.
I have already implemented a function to type in data what works great.
Only the function to load the json data is not working.
But i really don't know why.
I have posted the whole html code and my load data function.
MY Javascript code:
function loadData() {
var text = '{"employees":[' +
'{"firstName":"Ben","lastName":"dsafsad" },' +
'{"firstName":"Peter","lastName":"dsdsaadsj" },' +
'{"firstName":"Jules","lastName":"MIAU" }]}';
obj = JSON.parse(text);
for (var i = 0; i < obj.length; i++) {
var currentObj = obj[i];
var myName = currentObj.employees[0].firstName;
var age = currentObj.employees[0].lastName;
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
}
MY HTML code:
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" id="age">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()">
<input type="button" id="add" value="Load Data" onclick="Javascript:loadData()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
<div id="mydata">
<b>Current data in the system ...</b>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</table>
<br/>
</div>
</body>
</html>

You should be iterating over obj.employees, not obj. You have one object, which is composed of an employees array (with length of 3 in your example).
obj = JSON.parse(text);
console.log(obj);
console.log(obj.length); //this returns undefined
console.log(obj.employees.length); //this is what you want
for (var i = 0; i < obj.employees.length; i++) {
var currentObj = obj.employees[i];
console.log(currentObj);
var myName = currentObj.firstName;
console.log(myName);
var age = currentObj.lastName;
console.log(age);
}
Fiddle demo
You also have a problem here:
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
myName and age are variables you defined, not html elements, and as such, they don't have a value property. You just need to refer to the variables themselves, like so:
row.insertCell(1).innerHTML= myName;
row.insertCell(2).innerHTML= age;
Update Fiddle Demo

Related

JavaScript: text element returning "undefined"

I'm trying to retrieve the entered text in each textbox, by querying and looping through by ID tag.
But when I print what I have retrieved it outputs "undefined".
Looks like your post is mostly code:
</head>
<body bgcolor="#E6E6FA">
<font color=black size=+3>Modifying Sentiment</font>
<table>
<tr>
<td>Text to Save:</td>
</tr>
<tr>
<td colspan="3">
Add positive adjective:
<img Adjective src="http://findicons.com/files/icons/2776/android_icons/96/ic_question_mark.png" alt="question" title="Adjective: is a word naming an attribute of a noun, such as sweet, red, or technical."
width=20 />
<br>
<textarea cols=40 rows=3 id="textbox" ></textarea>
<textarea id="textbox" style="width:512px;height:256px"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button>
<td>
</tr>
</table>
<script type='text/javascript'>
function saveTextAsFile(){
var textBoxes = document.querySelectorAll('textbox');
var textToWrite;
for(var i in textBoxes){
textToWrite = textBoxes[i].value;
window.alert(textToWrite);
}
var textToWrite = document.getElementById("textbox").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
}
</script>
I have edited your javascript to point to textarea instead of textbox.
I also modified your for loop as I was getting additional outputs in the console. I also changed your alert to a console.log as jsbin was throwing an error of possible endless loop.
Try this:
function saveTextAsFile()
{
var textBoxes = document.querySelectorAll('textarea');
var textToWrite;
for(var i = 0; i < textBoxes.length; ++i){
textToWrite = textBoxes[i].value;
console.log(textToWrite);
}
textToWrite = document.getElementById("textarea").value;
var textFileAsBlob = new Blob([textToWrite],{type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
}
Trying using #textbox as this refers to the ID of the dom elements
Actually each id value in an html document should be unique. In your HTML code, I can see two id parameter with the same value "textbox". Try to change the first to "textbox-1" or whatever make sense to you but don't repeat the same value for id property and it should work.

Create Table dynamically and get back their values in jsp Page

I am working on a project using jsp and html, in which I am adding rows in table dynamically on addRow button click. After adding the rows I am getting the values of all rows in jsp page. But its not getting the values back on jsp page as the name of the parameter is not recognized by jsp page
I am using the following code. Suggest me where i have been stuck.
HTML code:
<!doctype html>
<html lang="en">
<head>
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "line"+(rowCount+1);
element1.value=""+(rowCount+1);
cell0.appendChild(element1);
document.getElementById("countofrows").value=table.rows.length;
}
</script>
</head>
<body>
<form name="" action="myjsp.jsp">
<table id="receiptTable">
<tr>
<td><input tye="text" name="line1" value="0"></td>
<input type="hidden" name="countofrows">
</tr>
</table>
<table>
<tr>
<input type="button" name="addrow" onClick="addRow('receiptTable')" value="Add Line">
</tr>
</table>
</form>
</body>
</html>
Following is the JSP scriptlet code
<%
int count=Integer.parseInt(request.getParameter("countofrows"));
for(int i=1 ; i<=count ; i++;) {
String value=request.getParameter("line"+i));
out.println(" value here is"+value);
}
%>
It's working fine for the default row element but getting null in case of adding row
Replace
<input type="hidden" name="countofrows">
with
<input type="hidden" name="countofrows" id="countofrows">
and try again.
How about this one
<script language="javascript">
function addRow(tableID,theForm)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "line"+(rowCount+1);
element1.value=""+(rowCount+1);
cell0.appendChild(element1);
theForm.countofrows.value=table.rows.length;
}
</script>
<form name="" action="myjsp.jsp">
<table id="receiptTable">
<tr>
<td>
<input tye="text" name="line1" value="0">
</td>
<input type="hidden" name="countofrows" id="countofrows" >
</tr>
</table>
<table>
<tr>
<input type="button" name="addrow" onClick="addRow('receiptTable',this.form)" value="Add Line">
</tr>
</table>
</form>

I have a table in jsp which have 5 rows and 3 colums and i wanted to print it in servlet how can i do this?

<script>
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= medicinename.value;
row.insertCell(2).innerHTML= time.value;
row.insertCell(3).innerHTML= duration.value;
row.insertCell(4).innerHTML= when.value;
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
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.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
</script>
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
here is JAVASCRIPT through which i add element in JSP table
here is my 4 field and table which display data inside JSP
hello = request.getParameter("");//what should i take here
System.out.println(hello);
You need to collect your table data in JavaScript by the use a form or Ajax to send this data to your servlet. You can't get the table data from request parameters in servlet unless you send it.
An example of form
<form action="login" method="post">
<input type="text" name="uname" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="button" >Login</button>
</form>
This form pass uname and password to login Servlet.
You can pass each data in table like this way...!
In servlet side you can use this code for fetch data
String uname = request.getParameter("uname");
String password = request.getParameter("password");
just try out..!
Since, you were using jQuery and Servlet but you edited your question and removed the code. But here is some code example using jQuery.
Sample Table :
<table id='table_id'>
<th>Column1</th><th>Column2</th>
<tr>
<td>1</td><td>2</td>
</tr>
<tr>
<td>3</td><td>4</td>
</tr>
</table>
First you need to iterate through your table in javascript, create a JSON object with table data. Probably like this (see the table structure given here)
<script type="text/javascript" >
function collectData(){
var tableData = [];
$('#table_id tr').each(function(){
var $this = $(this);
var tds = $this.find('td');
var i = 0;
//if we have data in that row
if(tds.length){
var rowData = {
column1:tds[0].innerHTML,
column2:tds[1].innerHTML,
}
tableData.push(rowData);
}
});
console.log(tableData);
// Send it via AJAX
$.ajax({
url: '/yourServletName', // Change name to your servlet
type: 'POST',
dataType: 'json',
data: {objarray: JSON.stringify(tableData)},
success: function(result) {
alert('SUCCESS');
}
});
}
JSON will be like :
{
[{'column1':1,'column2':2}, {'column1':3,'column2':4}]
}
Now in your servlet code access this data using
String tableArray = request.getParameter("objarray").
But you need to convert the JSON to Java Pojo Object. Create a class similar to your table and parse the JSON using any library like jackson or gson
public class TableData{
private String column1;
private String column2;
public String getColumn1(){
return column1;
}
public void setColumn1(String column1){
this.column1 = column1;
}
public String getColumn2(){
return column2;
}
public void setColumn2(String column2){
this.column2 = column2;
}
}
GSON tutorial is given here
As explained in another answer, either use input elements in form or use JSON object as given in another answer here.
Form input method
HTML or JSP
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<form action="yourServletName" method="post">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
<button type="submit" class="button" >Submit</button>
<!-- Update the rowCount on Submitting the button -->
<input type="hidden" id="rowCount" value="" />
</form>
</div>
JS File to add input in table, you can :
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= '<input type="text" name="'+'rowMedicine'+rowCount+'" value="'+medicinename.value+'" readonly />';
row.insertCell(2).innerHTML= '<input type="text" name="'+'rowTime'+rowCount+'" value="'+time.value+'" readonly />';
row.insertCell(3).innerHTML= '<input type="text" name="'+'rowDuration'+rowCount+'" value="'+duration.value+'" readonly />';
row.insertCell(4).innerHTML= '<input type="text" name="'+'rowWhen'+rowCount+'" value="'+when.value+'" readonly />';
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
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.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
In your servlet, use the request.getParameter to access values.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Now, you can get the parameter from input elements using name
String rowMedicine = request.getParameter("rowMedicine1");
//Similarly get the values of all parameters using names
//get the row count
//iterate through it and save it in your database
}

Javascript not giving alert after for loop

i have a javascript function which has foor loop in it. once the loop exists it is not displaying alert can anyone suggest what might be wrong.
the code is below
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<?PHP Include('Includes\common\header_items.php');
session_start();
?>
</head>
<body>
<form name="step2" method="POST">
<div id="qwe">
<table width="500px" id="myTable" name="myTable">
<thead>
<tr>
<td >Brawing / Document No.</th>
<td>Revision No.</th>
<td>Description (Optional)</th>
</tr>
</thead>
<tbody>
<tr>
<td width="40%"><input type="text" id="553" name="2" /></th>
<td width="10%"><input type="text" id="revID553" name="3" /></th>
<td width="45%"><input type="text" id="descpID553" name="4" /></th>
</tr>
<tr>
<td width="40%"><input type="text" id="4" name="21" /></th>
<td width="10%"><input type="text" id="15" name="31" /></th>
<td width="45%"><input type="text" id="6" name="41" /></th>
</tr>
<tr>
<td width="40%"><input type="text" id="556" name="2" /></th>
<td width="10%"><input type="text" id="revID556" name="3" /></th>
<td width="45%"><input type="text" id="descpID556" name="4" /></th>
</tr>
</tbody>
</table>
<input type="submit" onclick='Javascript: return testFunc();'>
</div>
</form>
<script language="javascript">
var table_row = [];
function testFunc(){
table_row.length = 0;
var count = 0;
var testing = document.getElementById("myTable").getElementsByTagName("input");
for (i=0; i<=testing.length; i++){
var data = document.getElementById("myTable").getElementsByTagName("input")[i].id;
if(data.substring(0,2) == "55")
{
var value_doc = document.getElementById("myTable").getElementsByTagName("input")[i].value;
var value_rev = 'revID'+data;
var rev = document.getElementById(value_rev).value;
var value_descp = 'descpID'+data;
var descp_data = document.getElementById(value_descp).value;
//code to add into array
table_row[count] = [data,rev,descp_data];
count ++;
}
}
alert("I am in the end");
</script>
</body>
</html>
i cant figure out why it is not displaying the last alert. Any suggestions? THe last alert is not working.
Hello Your code is working fine for me.
Write your function like this.
function testFunc(){
alert("I am in test function");
for (i=0; i<=5; i++){
//code to add values in array
// it displays the values added in array correctly
alert('call');
}
alert("Function is Ending"); //this is not displayed once loop runs 5 times.
return true;
}
Now Call your function in load.
$(document).ready(function () {
testFunc();
});
Fiddle Demo
You have not call your function :
JSFiddle
Check Below Code :
function testFunc(){
alert("I am in test function");
for (i=0; i<=5; i++){
//code to add values in array
// it displays the values added in array correctly
}
alert("Function is Ending"); //this is not displayed once loop runs 5 times.
return true;
}
testFunc(); // calling function
The main problem is in extra loop iteration.
I also rewrite code a little bit to avoid many document.getElementById("myTable").getElementsByTagName("input"), because it causes searching over DOM every time it appears.
<script language="javascript">
var table_row = [];
function testFunc() {
table_row.length = 0;
var count = 0;
var testing = document.getElementById("myTable").getElementsByTagName("input");
for (i = 0; i < testing.length; i++) {
var data = testing[i].id;
if (data.substring(0,2) == "55") {
var value_doc = testing[i].value;
var value_rev = 'revID' + data;
var rev = document.getElementById(value_rev).value;
var value_descp = 'descpID' + data;
var descp_data = document.getElementById(value_descp).value;
//code to add into array
table_row[count] = [data, rev, descp_data];
count ++;
}
}
alert("I am in the end");
}
</script>

Clone a table row and remove values in JavaScript

I have a set of text inputs fields which I want to be cloned when the user clicks the "add" button. My problem is that the fields are being cloned with the input from the user. Using Javascript, how do I reset the value of the text input fields so they may be cloned without cloning the user input text.
This is my code...
<table width="766" border="0" cellspacing="0" cellpadding="0" id="albumTable">
<tr id="clone">
<td width="230"><input type="text" name="dj_1" /></td>
<td width="230"><input type="text" name="affiliations_1" /></td>
<td width="230"><input type="text" name="rating_1" /></td>
<td width="230"><input type="text" name="comments_1" /><input type="hidden" name="count" value="1" class="count"/></td>
<td width="286" style="position:absolute; top:110px; left: 670px;"><input name="button" type="button" id="Add" value="ADD ROW" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table>
<script type="text/javascript">
function addRow(r){
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
var cInp = cRow.getElementsByTagName('input');
var countRow = cRow.getElementsByClassName('count');
for(var i=0;i<cInp.length;i++){
cInp[i].setAttribute('name',cInp[i].getAttribute('name').replace(/\d/g,(allRows.length+1)))
}
for(var j=0;j<countRow.length;j++){
countRow[j].setAttribute('value',countRow[j].getAttribute('value').replace(/\d/g,(allRows.length+1)))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
Something like this:
var cln = document.getElementByID("clone");
var clns = cln.getElementsByTagName("td");
for(var i = 0; i <clns.length; i++)
{
clns[i].innerHTML = "";
}
In the first for loop, just add this:
cInp[i].value='';

Categories

Resources