Store all data to 2D array - javascript

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.

Related

Displaying information from local data in a table

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>

Why my text box input disappear after I get my first data?

When I get my first data via my button the text boxes aren't there any more
and I don't have any errors
After clicking in the add button with no boxes on my page the new empty lines would be added on the top of my first data which has been added to my table but it should be added under my first data
function add()
{
var fname= document.getElementById('FirstName');
var lname= document.getElementById('LastName');
var person = document.createElement('tr');
var fn = document.createElement('td');
var fnNode = document.createTextNode(fname);
fn.appendChild(fname);
var ln = document.createElement('td');
var lnNode = document.createTextNode(lname);
ln.appendChild(lname)
person.appendChild(fn)
person.appendChild(ln)
document.getElementById('tbl').appendChild(person)
}
FirstName <input type ="text" id="FirstName" /> <br />
LastName <input type ="text" id="LastName" /> <br />
<input type ="button" value = "Add" onclick="add()"/><br />
<hr />
<table id="tbl" align="center" border="1" width ="400">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>
This should do it:
function add()
{
document.getElementById('tbl').innerHTML+='<tr><td>'
+document.getElementById('FirstName').value+'</td><td>'
+document.getElementById('LastName').value+'</td></tr>';
}
FirstName <input type ="text" id="FirstName" /> <br />
LastName <input type ="text" id="LastName" /> <br />
<input type ="button" value = "Add" onclick="add()"/><br />
<hr />
<table id="tbl" align="center" border="1" width ="400">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>
... write less, do more!
I don't know why you made it so complicated we can write it two lines but anyhow I've come up with elaborate solution here you go
function add() {
var fname= document.getElementById('FirstName').value;
var lname= document.getElementById('LastName').value;
let table = document.getElementById("tbl");
let row = table.insertRow(-1);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = fname;
cell2.innerHTML = lname;
}
FirstName <input type ="text" id="FirstName" /> <br />
LastName <input type ="text" id="LastName" /> <br />
<input type ="button" value = "Add" onclick="add()"/><br />
<hr />
<table id="tbl" align="center" border="1" width ="400">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>

How to delete an object from array on Button click?

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);

Javascript Validation (Input not showing after clicking Submit)

This is a simple code and I don't know where I went wrong.. Name validation works if no name is entered, but it doesn't show the result when a valid name is entered.
Here's my code:
I'm just new in html and javascript, hoping i'd get help from here. Thank you
function checkname(form) {
var eobj = document.getElementById('MITname');
var jname = form.Name.value;
var error = false;
eobj.innerHTML = '';
if (jname == '') {
error = "Name is required!";
var error2 = error.fontcolor("red");
}
if (error) {
if (hasFocus == false) {
form.Name.focus();
hasFocus = true;
}
eobj.innerHTML = error2;
return false;
}
return true;
}
function showinput() {
document.getElementById('namedisplay').innerHTML = document.getElementById('MITname').value;
}
function validate() {
hasFocus = false;
var form = document.forms['form'];
var ary = [checkname];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++) {
if (!ary[z0](form)) {
rtn = false;
}
}
return rtn;
}
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="submit" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Few issues here. (Also, welcome to Web Development!)
First, you never actually create the variable hasFocus. So you're never actually checking if it's true/false or not.
Second, where you create error2 means that it will only be accessible within the if() block it was created in. So, in the following if(error) block when you try to access it, it will return undefined.
Third, when you create error you are setting the value to false, which indicates a Boolean type, but then later setting its value to a String, which is definitely not a Boolean.
Fourth, the line var ary = [checkname]; is confusing to me. I get that you're trying to convert the name (from the input?) to an array, but that is not the way to do it. You can access each character of the name with string.charAt(index), so creating an array isn't really necessary.
Fifth, your validate() function as a whole is very confusing. I haven't a clue what you're trying to do. It looks like your teaching source may have mislead you, or you weren't paying attention that closely.
I could go on, however those (among other) issues are really making it difficult to find exactly what is going wrong, without digging too much into it. I don't want to write this for you, and so my suggestion would be to start again, and maybe checkout some more tutorials, perhaps from a different source. (Different youtube channel, etc.)
My problem is the validation. If I enter a blank name, an error message should appear next to the Name's text box indicating to enter a valid name.
<!DOCTYPE html>
<html>
<head>
<title>JAVASCRIPT FORM VALIDATION</title>
<script type="text/JavaScript">
function showMessage()
{
var Name = document.getElementById("Name").value;
displayname.innerHTML= Name;
var Email = document.getElementById("Email").value;
displayemail.innerHTML= Email;
var Website = document.getElementById("Website").value;
displaywebsite.innerHTML= Website;
var Comment = document.getElementById("Comment").value;
displaycomment.innerHTML= Comment;
var nameerror='';
var emailerror='';
var websiteerror='';
var commenterror='';
if (displayname.innerHTML=='')
{
nameerror = 'Please enter a valid name';
return false;
}
return true;
}
</script>
</head>
<body>
Name: <input type="text" id = "Name"> <span id = "nameerror"> </span>
<br></br>
Email: <input type="text" id = "Email">
<br></br>
Website: <input type="text" id = "Website">
<br></br>
Comnent: <textarea cols="35" rows="7" id="Comment"> </textarea>
<br></br>
<input type="submit" onclick="showMessage()" value="submit" />
<p>Name: <span id = "displayname"></span> </p>
<p>Email: <span id = "displayemail"></span> </p>
<p>Website: <span id = "displaywebsite"></span> </p>
<p>Comment: <span id = "displaycomment"></span> </p>
</body>
</html>
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="button" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Just remove type='submit' in your code it will submit your page while click once you click submit the data's are change to POST , So use button as type

On enter, search for the string in db

i have this code:
<body>
Please make your selection:
<div id="div1">
<tr>
<td>
<input type="button" value="Insert" onclick="form.html" />
</td>
<td>
<input type="button" value="View" onclick="window.location='view-master.php';" />
</td>
<td>
<input type="button" value="Edit" onclick="edit.html" />
</td>
<td>
<input type="button" value="Search" onclick="showsearchform()" />
</td>
</tr>
</div>
</body>
then the JS:
<script type="text/javascript">
function showsearchform()
{
var tr = document.createElement("tr");
var td = document.createElement("td");
var label = document.createElement("label");
label.id = "label1";
label.value = "Surname";
var input = document.createElement("input");
tr.appendChild(td);
td.appendChild(label);
td.appendChild(input);
var element = document.getElementById("div1");
element.appendChild(tr);
$('#input').keyup(function (e) {
var str = $('#search').val();
var url = "search.php";
if (e.keyCode == 13) {
location.href = url;
}
});
}
</script>
when i click on search i get the inoutbox, but what i want to do now is when i type a surname into the box and hit enter i want to connect to the db and search for this surname
I can do the db stuff just not sure of the JS and Jquery
html
<input type="text" name="txt" onkeypress="Search" />
javascript
<script>
function Search(e){
if(e.keyCode === 13){// enter key value is 13
**// Your ajax request write here , and in server side you can
**check corresponding results in database and return if data is present and take it as ajax replay****
}
return false;
}
</script>

Categories

Resources