I had majority of these functions working and now when i restarted my program they are saying undefined functions through chrome. Not sure the exact problem, im sure im missing something somewhere but its not coming up through eclipse. REALLY NEED HELP !!!! cant figure out the exact location or i would have shortened the files but i felt more is better than less in this instance where i cant find out where the code is breaking. Thank you all
HTML FILE
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="layout.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Manager Menu</title>
</head>
<body>
<div id = "header">
Welcome to the employee database;
</div>
<div id = "login">
Welcome <label id="welcomeLabel"></label>
<form action="http://localhost/Employee_12_14_13/login.html">
<input type="submit" value="Logout">
</form>
</div>
<div id = "buttons">
<br/><input type="submit" value="Create Group" onclick='createGroup()'>
<br/><input type="submit" value="Edit Employee" onclick='editEmployee()'>
<br/><input type="submit" value="Search for Employee" onclick='search()'>
<br/><input type="submit" value="View all employees" onclick='viewAll()'>
<br/><input type="submit" value="Delete Group" onclick='deleteGroup()'>
<br/><input type="submit" value="View all no group" onclick='viewNoGroup()'>
</div>
<div id ="createGroup" style="display:none">
<br/>Enter name of Group: <input type ="text" name="newGroup" id="newGroup">
<input type="submit" value="Enter">
</div>
<div id ="deleteGroup" style="display:none">
<br/>Enter name of Group: <input type ="text" name="newGroup" id="newGroup">
<input type="submit" value="Enter">
</div>
<div id ="Search" style="display:none">
<br/>Employee Email: <input type ="text" name ="toFind" id ="toFind">
<input type="submit" value="Enter" onclick='searchFor()'>
</div><div id ="editPersonalInfo" style="display:none">
<br/>Employee Email: <input type ="text" name="username" id="user">
<br/>Name: <input type="text" name ="name" id="name">
<input type="submit" value="Edit Name" onclick='editName()'>
<br/>Email address: <input type="text" name ="email" id="email">
<input type="submit" value="Edit Email" onclick='editEmail()'>
<br/>Password: <input type="password" name ="pass" id="pass">
<input type="submit" value="Edit Password" onclick='editPass()'>
<br/>Phone number: <input type="text" name ="phone" id="phone">
<input type="submit" value="Edit Phone" onclick='editPhone()'>
<br/>Programming Language: <input type="text" name ="username" id="user">
<form action="http://localhost/Employee_12_14_13/login.html">
<input type="submit" value="Logout">
</form>
<form action="http://localhost/Employee_12_14_13/menu.html">
<input type="submit" value="MainMenu">
</form>
</div>
<div id="employeePersonalInfo" style="display:none">
<br/>Id: <label id="id"></label>
<br/>Name: <label id="name"></label>
<br/>Email address: <label id="email"></label>
<br/>Phone number: <label id="phone"></label>
<form action="http://localhost/Employee_12_14_13/login.html">
<input type="submit" value="Return">
</form>
<form action="http://localhost/Employee_12_14_13/menu.html">
<input type="submit" value="Menu">
</form>
</div>
<div id="viewAllTable" style="border: 0px solid black"></div>
<div id="viewAllNoGroup" style="border: 0px solid black"></div>
<div id="viewAllInGroup" style="border: 0px solid black"></div>
<div id="searchTable" style="border: 0px solid black"></div>
</body>
<script src="./JS/managerMenu.js"></script>
</html>
JS
function GetRequest() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest = (strs[i].split("=")[1]);
}
}
return theRequest;
}
function changeLabel()
{
document.getElementById("welcomeLabel").innerHTML = GetRequest();
}
function createGroup()
{
}
function deleteGroup()
{
setAllInvis();
deleteGroupServlet(GetRequest());
}
function searchFor()
{
setAllInvis();
changeLabel();
callServlet(document.getElementById("toFind").value);
}
function setAllInvis()
{
document.getElementById("viewAllTable").style.display="none";
document.getElementById("viewAllInGroup").style.display="none";
document.getElementById("viewAllNoGroup").style.display="none";
document.getElementById("searchTable").style.display="none";
document.getElementById("createGroup").style.display="none";
document.getElementById("editPersonalInfo").style.display="none";
document.getElementById("Search").style.display="none";
document.getElementById("deleteGroup").style.display="none";
document.getElementById("editPersonalInfo").style.display="none";
document.getElementById("employeePersonalInfo").style.display="none";
}
function search()
{
setAllInvis();
document.getElementById("Search").style.display="block";
}
function editEmployee()
{
setAllInvis();
document.getElementById("editPersonalInfo").style.display="block";
}
function editName()
{
editServlet("name",document.getElementById("user").value,document.getElementById("name").value);
}
function editEmail()
{
editServlet("email",document.getElementById("user").value,document.getElementById("email").value);
}
function editGroup()
{
editServlet("group"),document.getElementById("user").value,document.getElementById("group").value;
}
function editPass()
{
editServlet("pass",document.getElementById("user").value,document.getElementById("pass").value);
}
function editPhone()
{
editServlet("phone",document.getElementById("user").value,document.getElementById("phone").value);
}
function viewEmployee()
{
viewEmployee(document.getElementById("toFind").value);
}
function viewNoGroup()
{
setAllInvis();
var http = new getXMLHttpRequestObject();
var url = "viewNoGroupServlet";
alert("viewNoGroup");
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
var jsonObj = JSON.parse(http.responseText);
viewNoGroupTable(jsonObj);
};
http.send();
}
function searchNoGroup()
{
viewNoGroup();
}
function next(){
setAllInvis();
var select = document.getElementById("managerMenu");
var index = select.selectedIndex;
var menuOption = select.options[index].value;
var username = GetRequest();
if(menuOption=="Search by email address"){
document.getElementById("username").value = "";
document.getElementById("message").style.display="none";
document.getElementById("search").style.display="block";
document.getElementById("viewAllTable").style.display="none";
}
else if(menuOption=="View all"){
document.getElementById("search").style.display="none";
document.getElementById("searchTable").style.display="none";
document.getElementById("viewAllTable").style.display="block";
viewAll();
}
}
function validateLogin(){
var username = document.getElementById("username").value;
callServlet(username);
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function getXMLHttpRequestObject() {
var xmlhttp = 0;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
// Opera 8.0+, Firefox, Chrome, Safari
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function editServlet(toEdit,email,changeTo)
{
var parameters = "username="+email+"&toChange="+toEdit+"&changeTo="+changeTo;
var http = new getXMLHttpRequestObject();
var url = "editInformationServlet";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.send(parameters);
}
function callServlet(username){
var http = new getXMLHttpRequestObject();
var url = "Menu";
var parameters = "username=" + username;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
var jsonObj = JSON.parse(http.responseText);
searchTable(jsonObj);
}
http.send(parameters);
}
function deleteGroupServlet(username){
var http = new getXMLHttpRequestObject();
var url = "deleteGroupServlet";
var parameters = "username="+username;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.send(parameters);
}
function addToGroup()
{
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
var email=data[3];
alert(email);
addToGroupServlet(email);
}
}
function addToGroupServlet(email);
{
var parameters = "username="+email+"&managerEmail="+GetRequest();
var http = new getXMLHttpRequestObject();
var url = "addToGroupServlet";
alert("In add to group");
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {// Handler function for call back on
if(http.readyState==4){
alert("addedToGroup");
ViewAllServlet();
}
http.send(parameters);
}
}
function deleteFromGroup(){
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
var email=data[3];
alert(email);
deleteFromGroupServlet(email);
}
}
function deleteFromGroupServlet(email)
{
var parameters = "username="+email;
var http = new getXMLHttpRequestObject();
var url = "deleteFromGroupServlet";
alert("In delete from group");
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {// Handler function for call back on
if(http.readyState==4){
alert("deletedFromGroup");
ViewAllServlet();
}
}
http.send(parameters);
}
function searchTable(jsonObj) {
var data = '';
data += '<table border=1><tbody><tr>';
data += '<th> ID </th>';
data += '<th> Name </th>';
data += '<th> Salary </th>';
data += '<th> Email address </th>';
data += '<th> Phone number </th>';
for (var i = 0; i < 1; i++) {
data += '<tr>';
data += '<td>' + jsonObj.id + '</td>';
data += '<td>' + jsonObj.name + '</td>';
data += '<td>' + jsonObj.salary + '</td>';
data += '<td>' + jsonObj.email + '</td>';
data += '<td>' + jsonObj.phone + '</td>';
data += '</tr>';
}
data += '</tbody><table>';
document.getElementById("searchTable").innerHTML = data;
}
function viewAll(){
ViewAllServlet();
}
function ViewAllServlet(){
var http = new getXMLHttpRequestObject();
var url = "viewAllServlet";
var email =GetRequest();
var parameters = "username="+email;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {// Handler function for call back on
if(http.readyState==4){
var jsonObj = JSON.parse(http.responseText);
viewAllTable(jsonObj);
setAllInvis();
document.getElementById("viewAllTable").style.display="block";
}
http.send(parameters);
}
}
function viewNoGroupTable(jsonObj)
{
var data = '';
data += '<table border=1><tbody><tr>';
data += '<th> ID </th>';
data += '<th> Name </th>';
data += '<th> Salary </th>';
data += '<th> Email address </th>';
data += '<th> Phone number </th>';
for (var i = 0; i < jsonObj.length; i++) {
data += '<tr>';
//for (var j = 0; j < colMax; j++) {
data += '<td>' + jsonObj[i].id + '</td>';
data += '<td>' + jsonObj[i].name + '</td>';
data += '<td>' + jsonObj[i].salary + '</td>';
data += '<td>' + jsonObj[i].email + '</td>';
data += '<td>' + jsonObj[i].phone + '</td>';
data += '<td><input type="submit" onclick="addToGroup()" value = Add To Group></td>';
//}
data += '</tr>';
}
data += '</tbody><table>';
alert("creating table");
document.getElementById('viewAllNoGroup').innerHTML = data;
document.getElementById('viewAllNoGroup').style.display="block";
}
function viewAllTable(jsonObj) {
var data = '';
data += '<table border=1><tbody><tr>';
data += '<th> ID </th>';
data += '<th> Name </th>';
data += '<th> Salary </th>';
data += '<th> Email address </th>';
data += '<th> Phone number </th>';
for (var i = 0; i < jsonObj.length; i++) {
data += '<tr>';
//for (var j = 0; j < colMax; j++) {
data += '<td>' + jsonObj[i].id + '</td>';
data += '<td>' + jsonObj[i].name + '</td>';
data += '<td>' + jsonObj[i].salary + '</td>';
data += '<td>' + jsonObj[i].email + '</td>';
data += '<td>' + jsonObj[i].phone + '</td>';
data += '<td><input type="submit" onclick="deleteFromGroup()" value = "Delete from Group"></td>';
//}
data += '</tr>';
}
data += '</tbody><table>';
document.getElementById('viewAllTable').innerHTML = data;
}
Not sure the exact problem, im sure im missing something somewhere but its not coming up through eclipse. REALLY NEED HELP !!!! cant figure out the exact location or i would have shortened the files but i felt more is better than less in this instance where i cant find out where the code is breaking. Thank you all
You have an error in your code that i pointed,
You have defined function and ended it using ;
function addToGroupServlet(email);
change above to
function addToGroupServlet(email)
move your:
<script src="./JS/managerMenu.js"></script> tags to the <head> section
you have ended function by ;
function addToGroupServlet(email){
//....
}
Related
//home html
<body>
<h2>Search Data from NYC Open Data Site</h2>
<h3>Choose One Dataset Below to Start Searching</h3>
<div>
<label class="datasets">Data Sets:</label> <br>
<input type="radio" id="data1" name="dataset" value="data1" required>
<label>Data1</label><br>
<input type="radio" id="data2" name="dataset" value="data2" required>
<label>Data2</label><br>
<input type="radio" id="data3" name="dataset" value="data3" required>
<label>Data3</label><br>
</div><br>
<h3 id="searchvalues"></h3>
<br>
<table id="searchresults"></table>
</body>
////1st html with search field and 2nd and 3rd as the same
`
<table>
<tr><td>ID</td><td><input type="text" size="20" id="idnumber"></td></tr>
<tr><td>Year</td><td><input type="text" size="20" id="year"></td></tr>
</table>
`I'm doing a program with 3 different html pages to search the data using Json link. I have 3 radio buttons which will be called on change to 3 separate html pages on my home html. But when I click on radio 1 , I only get the contents of one html no matter which radio button I click, eg- when I click on 1st radio button , instead of getting data3.html, I still get the contents of data1.html and no search data is appearing. I just started learning Ajax and Json 2 weeks ago. Any help would be much appreciated.
var xhr;
var r;
var asynchrequest;
var radioChoices;
window.addEventListener("load", registerListeners);
function registerListeners() {
radioChoices = document.getElementById("data1");
radioChoices = addEventListener("change", function () { getContent("Data1.html"); }, false);
radioChoices = document.getElementById("data2");
radioChoices = addEventListener("change", function () { getContent("Data2.html"); }, false);
radioChoices = document.getElementById("data3");
radioChoices = addEventListener("change", function () { getContent("Data3.html"); }, false);
}
function getContent(infopage) {
asynchrequest = new XMLHttpRequest(); //step 1
asynchrequest.open("GET", infopage, true); //step 2
asynchrequest.onreadystatechange = function () { //step 3
if (asynchrequest.readyState == 4 && asynchrequest.status == 200) {
document.getElementById("searchvalues").innerHTML = asynchrequest.responseText;
}
};
asynchrequest.send(); //step 4
}
function loadData1() {
//event listener
document.getElementById("idnumber").addEventListener("keyup", function () { searchIDNumber(this.value); }, false);
document.getElementById("year").addEventListener("keyup", function () { searchYear(this.value); }, false);
xhr = new XMLHttpRequest();
xhr.open("GET", "https://data.cityofnewyork.us/resource/4d7f-74pe.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
r = JSON.parse(xhr.responseText);
//displayData(r);
}
};
xhr.send();
}
function searchIDNumber(idnumber) {
//var r=JSON.parse(xhr.responseText);
document.getElementById("searchvalues").innerHTML = "Search by ID Number" + "<br>";
//structure table
var output = "<tr><th> ID </th><th> Fiscal Year </th><th> Organization Name </th><th> Status </th><th> Amount </th></tr>";
var searchid;
for (var i = 0; i < r.length; i++) {
var obj = r[i];
searchid = obj.mocs_id; // convert id to string from number value
if (searchid.startsWith(idnumber)) {
output += "<tr><td>";
output += obj.mocs_id;
output += "</td><td>";
output += obj.fiscal_year;
output += "</td><td>";
output += obj.legal_name_of_organization;
output += "</td><td>";
output += obj.status;
output += "</td><td>";
output += obj.amount;
}
}
document.getElementById("searchresults").innerHTML = output;
}
function searchYear(year) {
//var r=JSON.parse(xhr.responseText);
document.getElementById("searchvalues").innerHTML = "Search by Year" + "<br>";
//structure table
var output = "<tr><th> ID </th><th> Fiscal Year </th><th> Organization Name </th><th> Status </th><th> Amount </th></tr>";
var searchid;
for (var i = 0; i < r.length; i++) {
var obj = r[i];
searchid = obj.fiscal_year; // convert id to string from number value
if (searchid.startsWith(year)) {
output += "<tr><td>";
output += obj.mocs_id;
output += "</td><td>";
output += obj.fiscal_year;
output += "</td><td>";
output += obj.legal_name_of_organization;
output += "</td><td>";
output += obj.status;
output += "</td><td>";
output += obj.amount;
}
}
document.getElementById("searchresults").innerHTML = output;
}
I am trying to create a table dynamically using javascript. I want each table to have a checkbox beside it. So, I have written the following code:
JAVASCRIPT
label_submit_btn.addEventListener("click", function(event){
event.preventDefault();
var formInputs = document.getElementById("label_query_form").querySelectorAll("input");
validation = validateForm(formInputs);
if(validation[0]){
var label_query_form_action = document.getElementById("label_query_form").getAttribute("action");
var label_val = document.getElementById("label_no")
query_db("label_data_div", label_query_form_action, label_val, true, "label_query_row");
// var chk_boxes = document.getElementsByClassName("form-check-input");
// document.getElementById("data_delete_btn").disabled = false;
}
else{
alert(validation[1])
}
});
function query_db(output_div, form_action, form_data, add_checkbox, row_class){
document.getElementById(output_div).innerHTML = ""
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append(form_data.name, form_data.value)
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
let response_data = JSON.parse(this.responseText);
let table_data = JSON.parse(response_data);
table_data = create_table_from_json(table_data, add_checkbox, row_class);
document.getElementById(output_div).innerHTML += table_data;
}
}
xhr.open("POST", form_action, true);
xhr.send(formData);
}
function create_table_from_json(table_data, add_checkbox, row_class){
var table_rows = "";
for (var i = 0; i < table_data["columns"].length; i++) {
table_rows += "<th>" + table_data["columns"][i] + "</th>";
}
table_rows += "<th>Select</th>";
console.log(table_rows);
table_rows = "<tr>" + table_rows +"</tr>";
for (var i = 0; i < table_data["data"].length; i++) {
trow = ""
for (var j = 0; j < table_data["columns"].length; j++) {
trow += "<td class="+ table_data["columns"][j] +">" + table_data["data"][i][j] + "</td>";
}
if(add_checkbox == true){
trow += '<td><input type="checkbox" class="form-check-input"/> </td>';
}
table_rows += "<tr class="+ row_class + ">" + trow +"</tr>";
}
return "<table><tbody>" + table_rows + "</table></tbody>";
}
HTML
<div class="container" id="label_data_div" style="height: 200px;overflow: scroll;"></div>
Now, while rendering the page, all of the checkboxes are overflowing outside of the div element(see image).
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries');
this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "popultns" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var pop = el2.value;
if (country2)
{ // Add the new value
loadTableData.push(country2.trim() );
// Reset input value
el.value = '';
//el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
the image is the ui tht im working for the function
I'm supposed to auto-generate the table based on the data available from my main.js script which is in JSon format. There is no problem with the data loading since the data can be display in my html file. However, the problem comes whn my data is returned undefined on my auto generated table whn i click the 'add' button to update the data in the table. Whn i click in the edit button, the data is get correctly. only whn the display, it returns me undefined.
i know how alrdy.
here i attach the code & sample of the data i hv done.
hopefully this would help fresh grad like me who hv trouble in undrsntdng CRUD
<html>
<head>
<meta charset="UTF-8">
<title>Countries CRUD</title>
<style>
input[type='submit'], button, [aria-label]{
cursor: pointer;
}
#spoiler{
display: none;
}
</style>
</head>
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries' && 'popultns');
//this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "populations" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var popltn = el2.value;
if (country2 && popltn )
{ // Add the new value
//loadTableData.push(country2.trim() );
loadTableData.push({country: country2, population:popltn});
// Reset input value
el.value = '';
el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
this.Edit = function (item)
{ var el3 = document.getElementById('edit-name');
var el4 = document.getElementById('edit-popu');
// Display value in the field
let index = item;
el3.value = loadTableData[index].country;
el4.value = loadTableData[index].population;
// Display fields
document.getElementById('spoiler').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function()
{
// Get value
var country2 = el3.value;
var popltn = el4.value;
//console.log({country2, pop});
if (country2 || pop)
//console.log(country2);
{ // Edit value (strt,del,replace)
console.log(country2,popltn);
console.log(index, 1,({country2,popltn}));
//update array
loadTableData[index].country = el3.value;
loadTableData[index].population = el4.value;
//self.loadTableData.splice(index, 1,({country2,popltn}));
//console.log(index, 1, pop.trim());
//self.loadTableData.splice(index, 1, pop.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item)
{
// Delete the current row
loadTableData.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput()
{ document.getElementById('spoiler').style.display = 'none';}
</script>
</body>
</html>
How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementById("form");
//var device = document.getElementById('device').value;
//var j;
var obj = [];
for(j=0; j< cellData.length; j++)
{
obj += cellData[j].value;
}
var json = JSON.stringify(obj);
alert (json);
//document.getElementById('result').innerHTML = json;
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = document[method](item)
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
I am trying to fetch the json data fetched from a web service. I've fetched data successfully but I want to show it in a table form only after a button click.
The following code shows the name of table rows when the page is load.It should only appear after a button click.
Code:
<html>
<head>
<script language="javascript" type="text/javascript">
var request = null;
function createRequest()
{
try {
request = new XMLHttpRequest();
}
catch (trymicrosoft)
{
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
}
catch (othermicrosoft)
{
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage(lat,lon)
{
alert(lat);
createRequest();
;
var dis = document.getElementById("dt_id").value;
var url = "http://localhost:8080/testrestfullapi/webresources/drugController/getdata/"+dis;
alert(url);
request.open("GET", url, true);
request.onreadystatechange = handleResponse;
request.send(null);
}
function handleResponse()
{
if (request.readyState == 4){
alert("readystate=4");
var check=request.status;
alert(check);
alert(request.responseText);
if(check.toString()=="200")
alert("status ok");
var det = eval("(" + request.responseText + ")");
alert(det);
var data = "";
var i = 0;
for (var property in det) {
alert("Entered in for loop");
if (Object.prototype.hasOwnProperty.call(det, property)) {
data = data + "<tr>";
data = data + "<td class=\"sorting_1\">" + det[i].disease + "</td>";
data = data + "<td class=\" sorting_1\">" + det[i].drug + "</td>";
data = data + "<td class=\" sorting_1\">" + det[i].trade + "</td>";
i++;
}
}
document.getElementById("table_data").innerHTML = data;
}
}
</script>
</head>
<body>
<div style="text-align:left; margin:8px 5px auto;">
<label for="dt_id">Please enter disease </label>
<input type="Text" id="dt_id" maxlength="25" size="25"/>
<input type='button' onclick='getMessage()' value='SUBMIT'>
</div>
<table>
<thead>
<tr role="row">
<th>Disease</th>
<th>Drug</th>
<th>Trade</th>
</tr>
</thead>
<tbody id="table_data">
</tbody>
</table>
</body>
</html>
You forgot to hide the table initially. Hide the table by using this attribute style="display:none;" .. Then in button click you can show the table when you want...