I'm trying to perform a static crude operation. When user add a details on textbox it will stores in array of object and then that object print on table. Now I want to delete the row by delete button from array. I tried .splice() but it isn't working. The data is deleting from table but I want to delete it from array. I'm providing my page below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table With Bootstrap</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body><br><br><br>
<div class="container">
<h1 align="center">Enter Details</h1><br>
<div class="row">
<div class="col-sm-4">
<!--style="border:solid"-->
<div>
<label>Enter ID: </label><br>
<input type="number" class="form-control" id="id" name="id" required/>
<label>Enter Name: </label><br>
<input type="text" class="form-control" id="name" name="name" required/>
<label>Enter City: </label><br>
<input type="text" class="form-control" id="city" name="city" required />
<label>Enter Email: </label><br>
<input type="email" class="form-control" id="email" name="email" required/><br>
<button class="btn btn-success" onClick="printTable();">Submit</button> <button class="btn btn-danger" onClick="resetTable();">Reset Table</button></div>
</div>
<div class="col=sm-4">
<h1 style="color: white">Hello World heyy</h1>
</div>
<div class="col-sm-4" style="float: right;">
<table class="table table-sm table-striped table-hover table-bordered" style="border-radius: 5px;">
<thead class="thead-dark">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>User Email</th>
<th>User City</th>
<th>User Delete</th>
</tr>
</thead>
<tbody id="showResult">
</tbody>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
let data = [];
function resetTable() {
const confirmMessage = confirm("Are you sure want to reset table data? It will delete all data from table. You cannot undo this action.!");
if (confirmMessage) {
window.location.reload();
alert("Table Data Cleared Successfully");
} else {
alert("cancelled.!");
}
}
function printTable() {
const getId = document.getElementById("id").value;
const getName = document.getElementById("name").value;
const getCity = document.getElementById("city").value;
const getEmail = document.getElementById("email").value;
if (getId != '', getName != '', getCity != '', getEmail != '') {
const obj = {
id: getId,
name: getName,
city: getCity,
email: getEmail
}
data.push(obj);
print(data);
$('#id').val("");
$('#name').val("");
$('#city').val("");
$('#email').val("");
} else {
alert("All feilds are Mandatory..");
}
}
function print(data) {
let result = '';
for (let i = 0; i < data.length; i++) {
result += `
<tr id='row'>
<td>${data[i].id}</td>
<td>${data[i].name}</td>
<td>${data[i].email}</td>
<td>${data[i].city}</td>
<td><input type='button' onclick='deleteRow(this);' class='btn btn-danger' value='Delete'/></td>
</tr>`;
document.getElementById('showResult').innerHTML = result;
}
}
function deleteRow(btn) {
var cnfrmMessage = confirm("Are you sure want to Delete selected data? You cannot undo this action.");
if (cnfrmMessage == true) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
} else {
alert("Cancelled..!!");
}
}
</script>
</body>
</html>
I think you forget update your data array.
Change your deleteRow function to
function deleteRow(btn) {
var cnfrmMessage = confirm("Are you sure want to Delete selected data? You cannot undo this action.");
if(cnfrmMessage == true){
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
// update your data (remove item by row id)
data = data.filter((item)=>item.id!==$(row).children()[0].innerText);
}
else{
alert("Cancelled..!!");
}
}
Your array is literally a 'data'. So you need a unique id for delete specific row or do something on this.
Other way, you can compare all fields in that row you want to delete, but it's not a good solution.
You need a way to identify the item in the list going off of the HTML element. Looks like you can use the id column (although usually it would be better to put something like that in an attribute). Then you can use filter:
Add the id to the deleteRow function.
deleteRow(this, ${data[i].id})
// Removes item with id.
var a = [
{id:1},
{id:2},
{id:3},
{id:4},
{id:5},
{id:6},
{id:7},
{id:8},
{id:9}
];
a.filter(item => item.id != deleteId);
Related
When I click on the edit button, I want to edit the table data in the inputs.
the rest of the code is correct only thing that I need Is I want to edit the table data in the inputs
sorry for my bad english.
When I click on the edit button, I want to edit the table data in the inputs.
the rest of the code is correct only thing that I need Is I want to edit the table data in the inputs
sorry for my bad english.
var myContacts = [];
$(document).ready(function () {
let btn = $("#btn-1");
let btn2 = $("#btn-2");
let btn3 = $("#btn-3");
btn.click(function () {
let name = $("#name");
let age = $("#age");
let job = $("#job");
let address = $("#address");
let mobile = $("#mobile");
if (name.val().length > 0 && age.val().length > 0 && job.val().length > 0 && address.val().length > 0 && mobile.val().length > 0) {
contacts = {
name: name.val(),
age: age.val(),
job: job.val(),
address: address.val(),
mobile: mobile.val()
}
myContacts.push(contacts)
}else{
alert("plz fill the form")
};
document.getElementById("name").value = "";
document.getElementById("age").value = "";
document.getElementById("job").value = "";
document.getElementById("address").value = "";
document.getElementById("mobile").value = "";
console.log(myContacts);
});
btn2.click(function () {
showMyContacts(myContacts);
});
let btnRem = $(".btn_remove");
$(document).on('click', ".btn_remove", function () {
let index = $(this).data("index");
myContacts.splice(index, 1);
showMyContacts(myContacts);
});
let btnEddit = $(".btn_edit");
$(document).on('click', ".btn_remove", function () {
});
});
function showMyContacts(myContacts) {
let table = $("#my_table tbody");
table.html("");
for (let i = 0; i < myContacts.length; i++) {
table.append(`
<tr>
<td>${myContacts[i].name}</td>
<td>${myContacts[i].age}</td>
<td>${myContacts[i].job}</td>
<td>${myContacts[i].address}</td>
<td>${myContacts[i].mobile}</td>
<td><button data-index="${i}" class="btn btn-danger btn_remove">Remove</button></td>
<td><button data-index="${i}" class="btn btn-primary btn_edit">Edit</button></td>
</tr>
`);
};
};
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6">
<span>Name :</span>
<input id="name" type="text" class="d-flex mb-3">
<span>Age :</span>
<input id="age" type="number" class="d-flex mb-3">
<span>Job :</span>
<input id="job" type="text" class="d-flex mb-3">
<span>Address :</span>
<input id="address" type="text" class="d-flex mb-3">
<span>Mobile :</span>
<input id="mobile" type="tel" class="d-flex mb-3">
<button id="btn-1" class="mt-2">Save</button>
<button id="btn-2" class="mt-2">my Contacts</button>
</div>
<div class="col-md-6">
<table id="my_table" class="table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
<th>Address</th>
<th>Mobile</th>
<th>action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
I think this is what you are after, allows you to edit and save changes to each row, it's not the best code ever, just something I thew together quickly
let myContacts = [];
let edit = false;
$(document).ready(function() {
let btn = $("#btn-1");
let btn2 = $("#btn-2");
let btn3 = $("#btn-3");
btn.click(function() {
let name = $("#name");
let age = $("#age");
let job = $("#job");
let address = $("#address");
let mobile = $("#mobile");
if (name.val().length > 0 && age.val().length > 0 && job.val().length > 0 && address.val().length > 0 && mobile.val().length > 0) {
contacts = {
name: name.val(),
age: age.val(),
job: job.val(),
address: address.val(),
mobile: mobile.val()
}
myContacts.push(contacts)
} else {
alert("plz fill the form")
};
document.getElementById("name").value = "";
document.getElementById("age").value = "";
document.getElementById("job").value = "";
document.getElementById("address").value = "";
document.getElementById("mobile").value = "";
console.log(myContacts);
});
btn2.click(function() {
showMyContacts(myContacts);
});
let btnRem = $(".btn_remove");
$(document).on('click', ".btn_remove", function() {
let index = $(this).data("index");
myContacts.splice(index, 1);
showMyContacts(myContacts);
});
let btnEddit = $(".btn_edit");
$(document).on('click', ".btn_edit", function() {
if ($(this).text() === "Edit") {
$(this).text("Save")
$(this).closest("tr").find("td").each(function(index) {
if (index < 5)
$(this).attr('contenteditable', 'true');
})
} else {
let data = []
$(this).text("Edit")
var values = $(this).closest("tr").text()
.replace("Remove", "").replace("Edit", "")
.replace(/\r/g, "").split(/\n/);
jQuery.map(values, function(n, i) {
if ($.trim(n) !== "") {
data.push($.trim(n))
}
})
contacts = {
name: data[0],
age: data[1],
job: data[2],
address: data[3],
mobile: data[4]
}
myContacts[$(this).attr("data-index")] = contacts
console.log(myContacts)
$(this).closest("tr").find("td").each(function() {
$(this).attr('contenteditable', 'false');
})
}
});
});
function showMyContacts(myContacts) {
let table = $("#my_table tbody");
table.html("");
for (let i = 0; i < myContacts.length; i++) {
table.append(`
<tr>
<td>${myContacts[i].name}</td>
<td>${myContacts[i].age}</td>
<td>${myContacts[i].job}</td>
<td>${myContacts[i].address}</td>
<td>${myContacts[i].mobile}</td>
<td><button data-index="${i}" class="btn btn-danger btn_remove">Remove</button></td>
<td><button data-index="${i}" class="btn btn-primary btn_edit">Edit</button></td>
</tr>
`);
};
};
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6">
<span>Name :</span>
<input id="name" type="text" class="d-flex mb-3">
<span>Age :</span>
<input id="age" type="number" class="d-flex mb-3">
<span>Job :</span>
<input id="job" type="text" class="d-flex mb-3">
<span>Address :</span>
<input id="address" type="text" class="d-flex mb-3">
<span>Mobile :</span>
<input id="mobile" type="tel" class="d-flex mb-3">
<button id="btn-1" class="mt-2">Save</button>
<button id="btn-2" class="mt-2">my Contacts</button>
</div>
<div class="col-md-6">
<table id="my_table" class="table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
<th>Address</th>
<th>Mobile</th>
<th>action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
I hope this helps https://jsfiddle.net/kegh286u/
hello I'm working on a simple project where a user inputs the information and it goes into a table. I want the user to have the ability to put in the URL for an image and have it show up when the cell is made in the table. I have a button that prompts the user to input a URL but I cant figure out how to put that into an image tag inside the created cell.
let id = 0;
let img = document.getElementById("image").addEventListener("click", () => {
function getUrl() {
var url = prompt("Enter image URL");
if (url) {
return url;
} else {
return getUrl();
}
}
image.src = getUrl();
});
document.getElementById("add").addEventListener("click", () => {
let table = document.getElementById("list");
let row = table.insertRow(1);
row.setAttribute("id", `
test - $ {
id
}
`);
row.insertCell(0).innerHTML = document.getElementById("image").src = ""
row.insertCell(1).innerHTML = document.getElementById("Game-name").value;
row.insertCell(2).innerHTML = document.getElementById("hours-played").value;
row.insertCell(3).innerHTML = document.getElementById("new-critic-score").value;
row.insertCell(4).innerHTML = document.getElementById("new-personal-score").value;
let actions = row.insertCell(5);
actions.appendChild(createDeleteButton(id++));
document.getElementById("Game-name").value = "";
document.getElementById("hours-played").value = "";
document.getElementById("new-critic-score").value = "";
document.getElementById("new-personal-score").value = ""
});
function createDeleteButton(id) {
let btn = document.createElement("button");
btn.className = "btn btn-primary";
btn.id = id;
btn.innerHTML = "Delete";
btn.onclick = () => {
console.log(`
Deleting row with id: test - $ {
id
}
`);
let elementToDelete = document.getElementById(`
test - $ {
id
}
`);
elementToDelete.parentNode.removeChild(elementToDelete);
};
return btn;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" />
</head>
<body class="container" style="background-color: rgb(3, 27, 63);">
<!--Using HTML, Bootstrap, and JavaScript create a single page website that contains the following:
a. A Bootstrap styled table representing your choice of data.
b. A Bootstrap styled form that allows users to add input data as a new row to the table when submitted.
-->
<br />
<div class="card" style="background-color: rgb(7, 59, 75);color: rgb(255, 255, 255);">
<div class="card-body">
<div class="row">
<div class="col-sm">
<div>
<label for="new-critic-score">Critic score</label>
<input type="text" class="form-control" id="new-critic-score" placeholder="score out of 100" />
</div>
</div>
<div class="col-sm">
<div>
<label for="new-personal-score">Personal score</label>
<input type="text" class="form-control" id="new-personal-score" placeholder="score out of 100" />
</div>
</div>
<div class="col-sm">
<div>
<label for="hours-played">Hours played</label>
<input type="text" class="form-control" id="hours-played" placeholder="hours" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm">
<div>
<label for="Game-name">Game name</label>
<input type="text" class="form-control" id="Game-name" placeholder="Game title" />
</div>
</div>
</div>
<div class="col-sm">
<div> <br>
<button id="image" class="btn btn-secondary from-control">add image</button>
<button id="add" class="btn btn-primary from-control">Create</button>
</div>
</div>
</div>
</div>
<table id="list" class="table table-dark table-striped">
<tr>
<th>game image</th>
<th>games played</th>
<th>Hours played</th>
<th>critic score</th>
<th>personal score</th>
<th>Actions</th>
</tr>
</table>
<script src="index.js"></script>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
<img src="" alt="">
It wasn't clear to me how you wanted to do it, I basically got the URL and stored it in a var to then make another variable that is the image element itself, using the stored URL.
let imgURL;
let imgElement;
document.getElementById("image").addEventListener("click", () => {
imgURL = prompt("Enter image URL");
imgElement = '<img src="' + imgURL + '" width="80px">';
});
I also did the deletion in a similar way. Creating the element with an onclick to a function that passes the element itself with this as a parameter.
let deleteButton = '<input type="button" value="Delete" onclick="deleteRow(this)">'
and
row.insertCell(5).innerHTML = deleteButton;
Getting the ID by working your way up the parent elements to find the rowIndex.
function deleteRow(row) {
var id = row.parentNode.parentNode.rowIndex;
document.getElementById("list").deleteRow(id);
}
Hope the code itself helps you understand it better.
https://jsfiddle.net/sahil_m03/jmk4rbp3/43/
So I have a project to create a webpage that accepts user input on one page and displays it in a table on another page. I know at least some of the local storage is working because I called the 'textvalue' and it always has the user input correct. I can't seem to figure out why I can't get the data to display on the table though.
This is the code that I have to the page that takes the user input and throws it into local storage.
#page
#model RSVPModel
#{
ViewData["Title"] = "RSVP";
}
<h1>#ViewData["Title"]</h1>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content=" width=device-width, initial-scale=1.0" />
<title>RSVP</title>
<link rel="stylesheet" type=" text/css" href="style.css" />
<script>
function getDetails() {
var name = document.getElementById("name").value;
localStorage.setItem("textvalue", name);
var age = document.getElementById("age").value;
localStorage.setItem("agevalue", age);
var arrtime = document.getElementById("arrtime").value;
localStorage.setItem("timevalue", arrtime);
var parking = document.getElementById("parking").value;
localStorage.setItem("parkingvalue", parking);
return false;
if (!name || !age || !arrtime || !parking) {
alert("Please fill all fields before proceeding");
return;
}
}
</script>
</head>
<body>
<div id=" container">
<div class=" input">Name: <input id="name" type="text" /></div>
<div class=" input">Age: <input id="age" type="number" /></div>
<div class=" input">Arrival Time: <input id="arrtime" type="time" /></div>
<label for="parking">Request Parking?</label>
<select name="parking" id="parking">
<option value=""></option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<form action="Submitted">
<input type="submit" id="submit" value="Submit RSVP" onclick="getDetails();"/>
</form>
</div>
</body>
</html>
After the input page hitting the submit button will take them to a thank you page where they can navigate to the table page via a link on the page or the nav bar at the top of the page. Here is the code for that page.
#page
#model SubmittedModel
#{
ViewData["Title"] = "RSVP Submitted";
}
<body>
<div class="text-center">
<h1 class="display-4">Thank you <span id="result"></span>!</h1>
<p>It's great that you're coming. The drinks are already in the fridge!</p>
<p>Click here to see who is coming.</p>
</div>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
</body>
And this is the code I have for the page that tries to take that out of local storage, assign it to a variable, and then display it in the table.
#page
#model PrivacyModel
#{
ViewData["Title"] = "Here is a list of people attending the party";
}
<h1>#ViewData["Title"]</h1>
<body>
<script>
var row = 1;
var submit = document.getElementById('submit');
submit.addEventListener("click", displayDetails);
function displayDetails() {
document.getElementById("guestName").innerHTML = localStorage.getItem("textvalue");
document.getElementById("guestAge").innerHTML = localStorage.getItem("agevalue");
document.getElementById("arrivalTime").innerHTML = localStorage.getItem("timevalue");
document.getElementById("parkingRequest").innerHTML = localStorage.getItem("parkingvalue");
var display = document.getElementById("display");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = guestName;
cell2.innerHTML = guestAge;
cell3.innerHTML = arrivalTime;
cell4.innerHTML = parkingRequest;
row++;
}
</script>
<table id="display">
<tr>
<th>Name</th>
<th>Age</th>
<th>Arrival Time</th>
<th>Request Parking</th>
</tr>
</table>
</body>
I couldn't really find any information on a process like this, so I'm trying to piece together like 3 different tutorials. I might just need some fresh eyes to spot a simple mistake or I could be doing it completely wrong. Any help would be greatly appreciated.
I am not sure what happened on you code. If the following code is working, maybe you can modify it.
<body>
<div>
<span>Test</span><input type="text" id="input_test" size="14" value="new">
</div>
<div>
<button type="button" id="save">Save</button>
</div>
<div>
<button type="button" id="load">Load</button>
</div>
<table id="table_test">
<tr>
<th>test</th>
</tr>
</table>
</body>
<script>
let save = document.getElementById('save');
save.addEventListener("click", saveDetails);
function saveDetails() {
localStorage.setItem("Test", document.getElementById('input_test').value);
}
let load = document.getElementById('load');
load.addEventListener("click", loadDetails);
function loadDetails() {
let t = document.getElementById('table_test');
let r = t.insertRow(1);
let c = r.insertCell(0);
c.innerHTML = localStorage.getItem("Test");
}
</script>
I'm trying to save login credentials to HTML table (be patient please, I'm not a professional). I'm using push method to store the data but eventually, it stores only data of the last iteration because it was built around click function. So my question is how I store all credentials and not only the last one
<body>
<form name="login" class="diss">
Username<input type="text" name="userid" id="userName" />
Password<input type="password" name="pswrd" id="passw"/>
<input type="button" class="btn-dis" value="Login"/>
</form>
<table id="showAfter">
<tr>
<th>User Name</th>
<th>Password</th>
</tr>
</table>
<script src="firstMission.js"></script>
</body>
document.querySelector('.btn-dis').addEventListener('click', function()
x = document.getElementById("userName").value;
y = document.getElementById("passw").value;
table=document.getElementById('showAfter');
if (x=='' || y ==''){
alert("no can do");
restart();
}
else{
myTestArr.push([x,y]);
for(var i=0;i<myTestArr.length;i++)
{
var newRow = table.insertRow(table.length);
for(var j=0;j<myTestArr[i].length;j++)
{
var cell = newRow.insertCell(j);
cell.innerHTML=myTestArr[i][j];
}
}
}
mySecArr[i] = JSON.parse(JSON.stringify(myTestArr[i])); //copying to another
array
myTestArr.pop();
});
I'm not totally sure what you are going for here. But, given what I think you want, the following implementation will allow you to add new usernames and passwords to a table, while simultaneously storing them into an array.
const credentials = [];
document.querySelector('.btn-dis').addEventListener('click', function(e) {
let user = document.querySelector("#userName").value,
pass = document.querySelector("#passw").value,
table = document.querySelector("#showAfter");
if (!user && !pass) {
alert("no can do")
} else {
credentials.push([user, pass]);
var newRow = table.insertRow(table.length);
var cell = newRow.insertCell(0);
cell.innerHTML = user;
cell = newRow.insertCell(1);
cell.innerHTML = pass;
}
})
<body>
<form name="login" class="diss">
Username<input type="text" name="userid" id="userName" /> Password
<input type="password" name="pswrd" id="passw" />
<input type="button" class="btn-dis" value="Login" />
</form>
<table id="showAfter">
<tr>
<th>User Name</th>
<th>Password</th>
</tr>
</table>
</body>
That being said, saving credentials to memory is generally a bad practice, one which i would not recommend doing. But given you are a beginner, i'm going to make the assumption that this is for learning purposes only.
I am unable to split a variable that holds 5 fields from a form into a table in 5 different sections of the same row. I would appreciate any assistance.
// The section below this line is where the variable from the form input
// is inserted, but the role is not split into 5 different cells.
function getInfo() {
var info = document.getElementById("form1");
var text = "";
var i;
for (i=0; i < info.length; i++) {
text += info.elements[i].value;
}
document.getElementById("data").innerHTML = text;
// Log the form input into the console
console.log(text);
}
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
<!-- JQuery styling and CDN files -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Form HTML -->
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<p>Click the button below to display your entry.</p>
<!-- Javascript button to capture and display the input -->
<button onclick="getInfo()">Try it</button>
<table style="width:100%">
<tr>
<th>First Name</th>
</tr>
<tr id ="data">
</tr>
</table>
If you want the data into different columns, you have to create the columns and append them to a row.
You do not want to concatenate the data into a single var, because you want to keep the data split up into columns.
You could do this:
function getInfo() {
const info = document.getElementById("form1");
const row = document.getElementById("data");
for (let i =0; i < info.length; i++) {
// Make a new column
const col = document.createElement('td');
// Make a new text node
const colText = document.createTextNode(info.elements[i].value);
// Append text to column
col.appendChild(colText);
// Append column to the row (id of data)
row.appendChild(col);
}
}
You need to add the table cell markup to your string, given your current approach.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- JQuery styling and CDN files -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Custom css -->
<style>
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
</style>
<title>My Web Page</title>
</head>
<body>
<!-- Form HTML -->
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
<tr id ="data">
</tr>
</table>
<!-- Javascript function for the user input -->
<script type="text/javascript">
function getInfo() {
var info = document.getElementById("form1");
var text = "";
var i;
for (i=0; i < info.length; i++) {
text += "<td>"+info.elements[i].value+"</td>";
}
document.getElementById("data").innerHTML = text;
// Log the form input into the console
console.log(text);
}
</script>
<p>Click the button below to display your entry.</p>
<!-- Javascript button to capture and display the input -->
<button onclick="getInfo()">Try it</button>
</body>
</html>
Used the following methods, properties, and API:
HTMLFormControlsCollection
Array.from()
forEach()
.insertCell()
.textContent
Demo
Details are commented in Demo
function distData(e) {
//HTMLFormControlsCollection
var F = document.forms.form1;
var x = F.elements;
//Convert Collection into an array
var fieldArray = Array.from(x);
console.log(fieldArray);
//Reference tr#data
var R = document.getElementById('data');
//Each input in array will...
fieldArray.forEach(function(field, index) {
//Check if input has a value
if (field.value.length > 0) {
//Create a <td> snd insert it into R
var cell = R.insertCell(index);
//Copy the input value into cell
cell.textContent = field.value;
} else {
//if form control has no value ignore it
console.log('field has no value');
}
});
return false;
}
table {
margin: 0 auto 20px
}
table,
td {
border: 3px inset grey
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<style>
div.ui-input-text {
width: 200px
}
button {
width: 200px
}
</style>
</head>
<body>
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br> Last name: <input type="text" name="lname" id="lname1" required><br> Address: <input type="text" name="th>" id="address1" required><br> City: <input type="text" name="city" id="city1"
required><br> State: <input type="text" name="state" id="state1" required><br>
<button onclick='distData()' type='button'>DATA</button>
</form>
<p>Click the button below to display your entry.</p>
<table style="width:100%">
<tr>
<th colspan='2'>Name</th>
<th colspan='3'>Location</th>
</tr>
<tr>
<th>First</th>
<th>Last</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
The section below this line is where the variable from the form input is inserted, but the role is not split into 5 different cells.
<tr id="data">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</body>
</html>
The problem is that you are concatenating each field into a string; there is no delimiter in the string so there is no logical way to break it up. What you want to do instead is store each field in an array, then you can iterate over that to build up a HTML string, or better yet just use Array.prototype.join() to create the HTML for the cells you are creating.
function getInfo() {
var info = document.getElementById("form1");
var fields = []; // create an empty array
var i;
for (i=0; i < info.length; i++) {
fields.push(info.elements[i].value);
}
document.getElementById("data").innerHTML = '<td>' + fields.join('</td><td>') + '<td>';
}
document.getElementById('try-it').addEventListener('click', getInfo, false);
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<p>Click the button below to display your entry.</p>
<button id="try-it">Try it</button>
<table style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
<tr id ="data">
</tr>
</table>
This will work, but it produces a table that can only have one row of data in it; every time you hit "Try It" the existing data will be replaced. To add more than one row, instead of targeting a particular row and inserting cells into it, create an entire row and append it to the table. Since you are already using jQuery, I'm using it in the below example.
function getInfo() {
// Create an array containing the values of all of the fields.
// First, select all of the input elements inside of the form,
// Then, use .map() to extract their values, finally use .get() to
// turn the jQuery object into an array.
var fields = $('#form1 input').map(function () {
return this.value;
}).get();
// create a new row and append it to the table.
$('#display-table').append('<tr><td>' + fields.join('</td><td>') + '<td></tr>');
}
// instead of using in-line event handlers, attach it in your code.
$('#try-it').on('click', getInfo);
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<p>Click the button below to display your entry.</p>
<button id="try-it">Try it</button>
<table id="display-table" style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
</table>
More resources
jQuery API reference main page
jQuery learning center
.map()
.append()
.get()
Array.prototype.push