``I'm trying to get the json data stored in local storage. How to get the local storage data from one page to another page in the same domain?
In MainPage.html "user" is stored in localstorage and i'm printing the values
In AddEmploye.html the data is appended to user data stored in local storage, but when i go to MainPage.html the previous is displayed without data inserted in AddEmploye.html
How to overcome this issue.
Thank you.
MainPage.html
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
.header{
background-color:black;
position:relative;
top:0;
left:0;
width:100%;
}
.header h1{
color:white;
}
</style>
<body>
<div class="container-fluid">
<div class="header">
<h1>Employees</h1>
</div>
<!-- Add Employee area!-->
<div class="addButton">
<div class="row">
<div class="col-sm-10">
<h3>Employee Details</h3>
</div>
<div class="col-sm-2">
<form action="AddEmploye.html">
<button class="btn btn-success"><i class="fa fa-plus"></i> Add Employee</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-9">
<div class="row">
<div class="col-xs-">
<label class="col-sm-2" for="ex1"><strong>Show entries</strong></label>
</div>
<div class="col-sm-2">
<input class="form-control" id="number" type="number" value="10" placeholder="no of entries">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="row">
<div class="col-xs-1">
<label class="col-sm-2" for="ex1"><strong>Search</strong></label>
</div>
<div class="col-sm-8">
<input type="text" onkeyup="searchTable()" id="myInput" name="employe" width="20rem"placeholder="search for Employee" class="form-control">
</div>
</div>
</div>
</div>
</div>
<!-- Employee Details area-->
<div class="table-responsive" >
<table class="table table-bordered table-striped" id="myTable" data-pagination="true">
<thead>
<tr>
<th data-field="email">Email</th>
<th data-field="image">Image</th>
<th data-field="status">Is Active</th>
<th data-field="mobile">Mobile</th>
<th data-field="college">College</th>
<th data-field="name">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!--modal content-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header bg-success">
<h4>Toggle Employe Status</h4>
<button type="button" class="close" data-dismiss="modal">×</button><br>
</div>
<div class="modal-body">
<p style="color:red">Are you sure you want to disable this user?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!--Script for local storage -->
<script>
var user = {
"employee": [
{
"fName":"xxx",
"lName":"yyy",
"mobile":"12345678987",
"email":"xxx.xxx888#gmail.com",
"image":'<img src="/home/chintu/Pictures/max volume.png" height="90" width="90"><br>',
"college":"IIT",
"status":'<i class="fa fa-times-circle" style="color:red; font-size:3em" data-toggle="modal" data-target="#myModal"></i>'
},
{
"fName":"YYY",
"lName":"YYY",
"mobile":"98765434567",
"email":"yyy.yyy111#gmail.com",
"image":'<img src="/home/chintu/Pictures/max volume.png" height="90" width="90"><br>',
"college":"NIT",
"status":'<i class="fa fa-check-circle" style="color:green; font-size:3em" data-toggle="modal" data-target="#myModal"></i>'
},
]
};
var Data=JSON.stringify(user);
localStorage.setItem("userData", Data);
//get the stored data
var Name=localStorage.getItem("userData");
//parse the data to JSON
var Obj=JSON.parse(Name);
//for debugging
console.log(Obj);
var i;
var k=Obj.employee.length;
console.log(k);
for(i=0;i<k;i++){
var table = document.getElementById("myTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML=Obj.employee[i].email;
cell2.innerHTML=Obj.employee[i].image;
cell3.innerHTML=Obj.employee[i].status;
cell4.innerHTML=Obj.employee[i].mobile;
cell5.innerHTML=Obj.employee[i].college;
cell6.innerHTML='<button class="btn btn-warning" onclick="deleteRow(this)"><span style="color:white"><i class="fa fa-edit"></i> Delete</span></button>';
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
delete Obj.employee[0];
console.log(Obj);
}
</script>
<!--Javascipt -->
<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>
</body>
</html>
AddEmploye.html
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
.header{
background-color:black;
position:relative;
top:0;
left:0;
width:100%;
}
.header h1{
color:white;
}
</style>
<body>
<div class="container-fluid">
<div class="header">
<h1>Add Employees</h1>
</div>
<h2>Add Employee</h2>
<form name="details" onsubmit="addDetails()" method="post">
<div class="row">
<div class="col-sm-6">
<strong><label for="FirstName">FirstName *</label></strong>
<input type="text" class="form-control" name="fname">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Branch *</label></strong>
<select class="form-control" placeholder="--Select Branch--" name="branch">
<option class="form-control" value="CSE">CSE</option>
<option class="form-control" value="ECE">ECE</option>
<option class="form-control" value="IT">IT</option>
<option class="form-control" value="MANAGEMENT">MANAGEMENT</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="FirstName">LastName *</label></strong>
<input type="text" class="form-control" name="lname">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Date of Joining *</label></strong>
<input type="date" name="date" class="form-control">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="FirstName">Mobile Number *</label></strong>
<input type="text" class="form-control" name="mobile">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Stream *</label></strong>
<select class="form-control" placeholder="--Select Branch--" name="stream">
<option class="form-control" value="CSE">CSE</option>
<option class="form-control" value="ECE">ECE</option>
<option class="form-control" value="IT">IT</option>
<option class="form-control" value="MANAGEMENT">MANAGEMENT</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Date of Birth *</label></strong>
<input type="date" name="dob" class="form-control">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Language *</label></strong>
<select class="form-control" placeholder="--Select Language--" name="language">
<option class="form-control" value="Telugu">Telugu</option>
<option class="form-control" value="English">English</option>
<option class="form-control" value="Hindi">Hindi</option>
<option class="form-control" value="Oriya">Oriya</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Email *</label></strong>
<input type="email" name="email" class="form-control">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Photograph *</label></strong>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Gender *</label></strong><br>
<input name="gender" value="male" type="radio"/>
<label for="male">Male </label>
<input name="gender" value="female" type="radio"/>
<label for="female">Female </label>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">College *</label></strong>
<select class="form-control" placeholder="--Select College--" name="college">
<option class="form-control" value="RGUKT">RGUT</option>
<option class="form-control" value="VIT">VIT</option>
<option class="form-control" value="IIIT">IIIT</option>
<option class="form-control" value="IIT">IIT</option>
</select>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Qualification *</label></strong>
<select class="form-control" placeholder="--Select College--" name="qualification">
<option class="form-control" value="BTECH">BTech</option>
<option class="form-control" value="MTECH">MTech</option>
<option class="form-control" value="MBA">MBA</option>
</select>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Year of Graduation *</label></strong>
<select class="form-control" placeholder="--Select Year--" name="yog">
<option class="form-control" value="2017">2017</option>
<option class="form-control" value="2018">2018</option>
<option class="form-control" value="2019">2019</option>
</select>
</div>
<div class="col-sm-6">
<strong><label for="DOB"> </label></strong><br>
<button class="btn btn-success"type="submit">Add</button>
</div>
</div>
</form>
</div>
<script>
var Name=localStorage.getItem("userData");
var Obj=JSON.parse(Name);
console.log(Obj);
function addDetails(){
var fName=document.details.fname.value;
var lName=document.details.lname.value;
var branch=document.details.branch.value;
var mobile=document.details.mobile.value;
var doj=document.details.date.value;
var stream=document.details.stream.value;
var dob=document.details.dob.value;
var language=document.details.language.value;
var email=document.details.email.value;
var gender=document.details.gender.value;
var college=document.details.college.value;
var qualification=document.details.qualification.value;
var yog=document.details.yog.value;
Obj.employee.push(
{
"fName":fName,
"lName":lName,
"mobile":mobile,
"email":email,
"image":'<img src="/home/chintu/Pictures/max volume.png" height="90" width="90"><br>',
"college":college,
"status":'<i class="fa fa-check-circle" style="color:green; font-size:3em" data-toggle="modal" data-target="#myModal"></i>'
}
);
console.log(Obj);
var Data=JSON.stringify(Obj);
//store the string format data in local storage
localStorage.setItem("userData", Data);
window.location='MainPage.html';
}
</script>
</body>
</html>
Solution
In MainPage.html I noticed you were running localStorage.setItem("userData", Data);, well this would override any data that's being added from AddEmploye.html, so what I did was check to see if userData existed in the localStorage, if not, then set it, otherwise continue.
You need to be aware, using setItem will just flat out override the data, not append to it. It's like doing the following:
var arr = [1];
arr = [2];
Whereas you want to be doing something more like:
var arr = [];
arr.push(1);
arr.push(2);
Edit
Turns out your solution was already kinda there, it was just one of those silly mistakes! Don't worry, even the best of us do silly things like this from time to time.
Hope this fixes your problem! :)
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
.header{
background-color:black;
position:relative;
top:0;
left:0;
width:100%;
}
.header h1{
color:white;
}
</style>
<body>
<div class="container-fluid">
<div class="header">
<h1>Employees</h1>
</div>
<!-- Add Employee area!-->
<div class="addButton">
<div class="row">
<div class="col-sm-10">
<h3>Employee Details</h3>
</div>
<div class="col-sm-2">
<form action="AddEmploye.html">
<button class="btn btn-success"><i class="fa fa-plus"></i> Add Employee</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-9">
<div class="row">
<div class="col-xs-">
<label class="col-sm-2" for="ex1"><strong>Show entries</strong></label>
</div>
<div class="col-sm-2">
<input class="form-control" id="number" type="number" value="10" placeholder="no of entries">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="row">
<div class="col-xs-1">
<label class="col-sm-2" for="ex1"><strong>Search</strong></label>
</div>
<div class="col-sm-8">
<input type="text" onkeyup="searchTable()" id="myInput" name="employe" width="20rem"placeholder="search for Employee" class="form-control">
</div>
</div>
</div>
</div>
</div>
<!-- Employee Details area-->
<div class="table-responsive" >
<table class="table table-bordered table-striped" id="myTable" data-pagination="true">
<thead>
<tr>
<th data-field="email">Email</th>
<th data-field="image">Image</th>
<th data-field="status">Is Active</th>
<th data-field="mobile">Mobile</th>
<th data-field="college">College</th>
<th data-field="name">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!--modal content-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header bg-success">
<h4>Toggle Employe Status</h4>
<button type="button" class="close" data-dismiss="modal">×</button><br>
</div>
<div class="modal-body">
<p style="color:red">Are you sure you want to disable this user?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!--Script for local storage -->
<script>
var user = {
"employee": [
{
"fName":"xxx",
"lName":"yyy",
"mobile":"12345678987",
"email":"xxx.xxx888#gmail.com",
"image":'<img src="/home/chintu/Pictures/max volume.png" height="90" width="90"><br>',
"college":"IIT",
"status":'<i class="fa fa-times-circle" style="color:red; font-size:3em" data-toggle="modal" data-target="#myModal"></i>'
},
{
"fName":"YYY",
"lName":"YYY",
"mobile":"98765434567",
"email":"yyy.yyy111#gmail.com",
"image":'<img src="/home/chintu/Pictures/max volume.png" height="90" width="90"><br>',
"college":"NIT",
"status":'<i class="fa fa-check-circle" style="color:green; font-size:3em" data-toggle="modal" data-target="#myModal"></i>'
},
]
};
var Data=JSON.stringify(user);
if (localStorage.getItem("userData") === null || typeof localStorage.getItem("userData") === "undefined") {
localStorage.setItem("userData", Data);
}
//get the stored data
var Name=localStorage.getItem("userData");
//parse the data to JSON
var Obj=JSON.parse(Name);
//for debugging
console.log(Obj);
var i;
var k=Obj.employee.length;
console.log(k);
for(i=0;i<k;i++){
var table = document.getElementById("myTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML=Obj.employee[i].email;
cell2.innerHTML=Obj.employee[i].image;
cell3.innerHTML=Obj.employee[i].status;
cell4.innerHTML=Obj.employee[i].mobile;
cell5.innerHTML=Obj.employee[i].college;
cell6.innerHTML='<button class="btn btn-warning" onclick="deleteRow(this)"><span style="color:white"><i class="fa fa-edit"></i> Delete</span></button>';
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
delete Obj.employee[0];
console.log(Obj);
}
</script>
<!--Javascipt -->
<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>
</body>
</html>
Edit 2
I have the solution to redirect the user to MainPage.html included below.
AddEmployee.html
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
.header{
background-color:black;
position:relative;
top:0;
left:0;
width:100%;
}
.header h1{
color:white;
}
</style>
<body>
<div class="container-fluid">
<div class="header">
<h1>Add Employees</h1>
</div>
<h2>Add Employee</h2>
<form name="details" onsubmit="return addDetails();" method="post">
<div class="row">
<div class="col-sm-6">
<strong><label for="FirstName">FirstName *</label></strong>
<input type="text" class="form-control" name="fname">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Branch *</label></strong>
<select class="form-control" placeholder="--Select Branch--" name="branch">
<option class="form-control" value="CSE">CSE</option>
<option class="form-control" value="ECE">ECE</option>
<option class="form-control" value="IT">IT</option>
<option class="form-control" value="MANAGEMENT">MANAGEMENT</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="FirstName">LastName *</label></strong>
<input type="text" class="form-control" name="lname">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Date of Joining *</label></strong>
<input type="date" name="date" class="form-control">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="FirstName">Mobile Number *</label></strong>
<input type="text" class="form-control" name="mobile">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Stream *</label></strong>
<select class="form-control" placeholder="--Select Branch--" name="stream">
<option class="form-control" value="CSE">CSE</option>
<option class="form-control" value="ECE">ECE</option>
<option class="form-control" value="IT">IT</option>
<option class="form-control" value="MANAGEMENT">MANAGEMENT</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Date of Birth *</label></strong>
<input type="date" name="dob" class="form-control">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Language *</label></strong>
<select class="form-control" placeholder="--Select Language--" name="language">
<option class="form-control" value="Telugu">Telugu</option>
<option class="form-control" value="English">English</option>
<option class="form-control" value="Hindi">Hindi</option>
<option class="form-control" value="Oriya">Oriya</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Email *</label></strong>
<input type="email" name="email" class="form-control">
</div>
<div class="col-sm-6">
<strong><label for="FirstName">Photograph *</label></strong>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Gender *</label></strong><br>
<input name="gender" value="male" type="radio"/>
<label for="male">Male </label>
<input name="gender" value="female" type="radio"/>
<label for="female">Female </label>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">College *</label></strong>
<select class="form-control" placeholder="--Select College--" name="college">
<option class="form-control" value="RGUKT">RGUT</option>
<option class="form-control" value="VIT">VIT</option>
<option class="form-control" value="IIIT">IIIT</option>
<option class="form-control" value="IIT">IIT</option>
</select>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Qualification *</label></strong>
<select class="form-control" placeholder="--Select College--" name="qualification">
<option class="form-control" value="BTECH">BTech</option>
<option class="form-control" value="MTECH">MTech</option>
<option class="form-control" value="MBA">MBA</option>
</select>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<strong><label for="DOB">Year of Graduation *</label></strong>
<select class="form-control" placeholder="--Select Year--" name="yog">
<option class="form-control" value="2017">2017</option>
<option class="form-control" value="2018">2018</option>
<option class="form-control" value="2019">2019</option>
</select>
</div>
<div class="col-sm-6">
<strong><label for="DOB"> </label></strong><br>
<button class="btn btn-success"type="submit">Add</button>
</div>
</div>
</form>
</div>
<script>
var Name=localStorage.getItem("userData");
var Obj=JSON.parse(Name);
console.log(Obj);
function addDetails(){
var fName=document.details.fname.value;
var lName=document.details.lname.value;
var branch=document.details.branch.value;
var mobile=document.details.mobile.value;
var doj=document.details.date.value;
var stream=document.details.stream.value;
var dob=document.details.dob.value;
var language=document.details.language.value;
var email=document.details.email.value;
var gender=document.details.gender.value;
var college=document.details.college.value;
var qualification=document.details.qualification.value;
var yog=document.details.yog.value;
Obj.employee.push(
{
"fName":fName,
"lName":lName,
"mobile":mobile,
"email":email,
"image":'<img src="/home/chintu/Pictures/max volume.png" height="90" width="90"><br>',
"college":college,
"status":'<i class="fa fa-check-circle" style="color:green; font-size:3em" data-toggle="modal" data-target="#myModal"></i>'
}
);
console.log(Obj);
var Data=JSON.stringify(Obj);
//store the string format data in local storage
localStorage.setItem("userData", Data);
window.location='MainPage.html';
return false;
}
</script>
</body>
</html>
Edit 3
This seems to work just fine for myself. I highly suggest you look at re-writing this function, just because I banged this together in like 30 seconds, it's messy, I appreciate that, but nevertheless it works.
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
delete Obj.employee[0];
var employees = JSON.parse(localStorage.getItem("userData")).employee.reverse();
var tempArray = [];
for (var j = - 1, s = employees.length - 1; j < s; s--) {
if (s !== (i - 1)) { tempArray.push(employees[s]); }
}
employees = tempArray;
var update = JSON.stringify({employee:employees});
localStorage.setItem("userData", update);
}
Edit 4
Okay, I'm not sure if this is 100% bullet proof, I've only vaguely tested it.
But I was just playing around with the JS inside of MainPage.html and I came up with this, it worked for my tests that I threw at it, but again, I've not done detailed testing, I'm sure that if you notice any bugs, you'll be able to sort them out? ;)
FYI I've rushed the hell outta this just to help you, I know it works to SOME degree or another, but if you notice any bugs, again, I'm sure you can work it out? ... If not, drop me an email and I'll re-do the whole thing for you, I'll even encapsulate it all into one nice object! ;)
... Also seeing as I've given you a link to my website, I suggest that you go on there and check out the git link that's provided on my web page... Take a look at the wishlist implementation, I appreciate I rammed everything into one large file, so if you struggle to find it, just press ctrl + f 'WishList', I've implemented a generic wishList using local storage! :P
var i;
var MAX_ROWS = 5;
var indentations = [0, MAX_ROWS];
var k=Obj.employee.length;
console.log(k);
for(i = k-1; i > 0; i--){
var table = document.getElementById("myTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML=Obj.employee[i].email;
cell2.innerHTML=Obj.employee[i].image;
cell3.innerHTML=Obj.employee[i].status;
cell4.innerHTML=Obj.employee[i].mobile;
cell5.innerHTML=Obj.employee[i].college;
cell6.innerHTML='<button class="btn btn-warning" onclick="deleteRow(this)"><span style="color:white"><i class="fa fa-edit"></i> Delete</span></button>';
if (i <= MAX_ROWS) {
var endVal = indentations[indentations.length - 1];
if (i % 5 === 0) { indentations.push(i + MAX_ROWS); }
else if (endVal < k && i == 1) {
endVal = endVal + MAX_ROWS;
indentations.push(endVal);
}
}
}
renderTbl(0, 5);
console.log(indentations);
var before = document.getElementById("myModal");
for (var j = 0, s = indentations.length; j < s; j++) {
var start = indentations[j];
var end = start + MAX_ROWS;
var btn = document.createElement("div");
btn.className = "btn";
btn.innerHTML = start + " ... " + end;
before.insertAdjacentElement("beforeBegin", btn);
}
var btns = document.querySelectorAll(".btn");
for (var j = 0, s = btns.length; j < s; j++) {
var btn = btns[j];
btn.addEventListener("click", function(){
var arr = this.textContent.split("...");
var start = arr[0];
var end = arr[1];
renderTbl(start, end);
});
}
function renderTbl (start, end, arr) {
var table = document.getElementById("myTable");
var rows = table.querySelectorAll("tr");
console.log(rows);
end = parseInt(end);
start = parseInt(start) + 1;
console.log(start) + 1;
console.log(end);
for (var i = 0; i < k; i++) {
console.log(rows[i].innerHTML);
if (i < start || i > end) {
rows[i].style.display = "none";
} else {
rows[i].style.display = "table-row";
}
}
rows[0].style.display = "table-row";
}
Related
I was able to get the value for Description (textarea) from the first service (selected input) (which is right), for the attribute of data id, but I'm having a problem getting it from appended elements, after using the add more button
What am I missing, please?
Below is my code and I can explain further if need be.
<div class="service-box">
<div class="row">
<div class="col-md-12 service-group">
<div class="row">
<div class="form-group mb-3 col-md-6">
<label class="form-label">Service</label>
<div >
<select type="text" class="form-select" placeholder="Services" value="" name="service" id="service">
<option value="" disabled selected>Select your option</option>
#foreach ($services as $service)
<option value="{{$service->service_name}}" data-id="{{$service->description}}">{{$service->service_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group mb-3 col-md-6">
<label class="form-label">Amount</label>
<div >
<input type="text" class="form-control" name="amount" id="amount" placeholder="Amount">
</div>
</div>
<div class="form-group mb-3 col-md-12">
<label class="form-label">Description</label>
<textarea class="form-control" id="description" name="description" rows="6" placeholder="Content.." readonly></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" id="addmore" class="btn btn-default">Add more</button>
<button type="button" id="remove" class="btn btn-default">Remove</button>
</div>
$("#addmore").click(function() {
var serviceGroupHTML = $('.service-group').html();
$( ".service-box" ).append(serviceGroupHTML);
});
$("#remove").on("click", function() {
$(".service-box").children().last().remove();
});
<!-- This is where the problem lies -->
const service = new Array(document.getElementById("service"));
const description = new Array(document.getElementById("description"));
service[0].addEventListener("change", function(){
description[0].value = $('#service option:selected').data('id');
})
service[1].addEventListener("change", function(){
description[1].value = $('#service option:selected').data('id');
})
As your newly created element are dynamic so you need to bind it with static element. Then, you can get the value of the data-attribute by using $(this).find("option:selected").data("id") and assign this to your textarea of that particular group .
Demo Code :
$("#addmore").click(function() {
$('.service-group:first').clone().find("input:text,textarea").val("").end()
.appendTo('.service-box');
});
$("#remove").on("click", function() {
$(".service-box").children().last().remove();
});
$("body").on("change", "select[name=service]", function() {
//get description for data-attribute
var description = $(this).find("option:selected").data("id");
//assign value
$(this).closest(".service-group").find("textarea[name=description]").val(description)
})
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="service-box">
<div class="row service-group">
<div class="col-md-12">
<div class="row">
<div class="form-group mb-3 col-md-6">
<label class="form-label">Service</label>
<div>
<select type="text" class="form-select" placeholder="Services" value="" name="service">
<option value="" disabled selected>Select your option</option>
<option value="1" data-id="This test">XYZ</option>
<option value="1" data-id="This test22">Z22</option>
<option value="1" data-id="This test33">YZ33</option>
</select>
</div>
</div>
<div class="form-group mb-3 col-md-6">
<label class="form-label">Amount</label>
<div>
<input type="text" class="form-control" name="amount" id="amount" placeholder="Amount">
</div>
</div>
<div class="form-group mb-3 col-md-12">
<label class="form-label">Description</label>
<textarea class="form-control" name="description" rows="6" placeholder="Content.." readonly></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" id="addmore" class="btn btn-default">Add more</button>
<button type="button" id="remove" class="btn btn-default">Remove</button>
</div>
I am trying to implement the search filter for the following application using angularjs. But it's not working as intended. I am new to this so I am not sure what I've done wrong here. Can someone help?
Here is my code so far:-
index.html file :
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="Controller/app.js"></script>
<script src="Controller/storage.js"></script>
</head>
<body ng-app="kfgPm">
<div ng-controller="MainCtrl" class="container">
<form name="kfgPmForm" ng-submit="submitForm(kfgPmForm.$valid)" novalidate>
<div class="col-sm-12" class="form-horizontal" role="form">
<div class="form-group col-sm-6">
<label for="projectID" class="col-sm-3 col-form-label">Project ID: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="projectID" required ng-model="itm.projectID">
</div>
</div>
<div class="form-group col-sm-6">
<label for="projectName" class="col-sm-3 col-form-label">Project Name: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="projectName" required ng-model="itm.projectName">
</div>
</div>
</div>
<div class="col-sm-12" class="form-horizontal" role="form">
<div class="form-group col-sm-6">
<label for="projectOwner" class="col-sm-3 col-form-label">Project Owner: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="projectOwner" required ng-model="itm.projectOwner">
</div>
</div>
<div class="form-group col-sm-6">
<label for="keyStake" class="col-sm-3 col-form-label">Key Stakeholders: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="keyStake" required ng-model="itm.keyStake">
</div>
</div>
</div>
<div class="col-sm-12" class="form-horizontal" role="form">
<div class="form-group col-sm-6">
<label for="prepBy" class="col-sm-3 col-form-label">Prepared By: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="prepBy" required ng-model="itm.prepBy">
</div>
</div>
<div class="form-group col-sm-6">
<label for="reqDate" class="col-sm-3 col-form-label">Requested Date: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="reqDate" required ng-model="itm.reqDate">
</div>
</div>
</div>
<div class="col-sm-12" class="form-group" ng-submit="submitDetails()" role="form">
<div class="form-group col-sm-6" class="input-group mb-3">
<label for="inputGroupSelect01" class="col-sm-3 col-form-label">Status: </label>
<div class="col-sm-9">
<select name="status" class="form-control custom-select" ng-options="user.option for user in arrlist" required ng-model="user.itm.status">
<option value="">Select..</option>
</select>
</select>
</div>
</div>
<div class="form-group col-sm-6">
<label for="dept" class="col-sm-3 col-form-label">Department: </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="dept" required ng-model="itm.dept">
</div>
</div>
</div>
<div class="col-sm-12" class="form-group purple-border">
<div class="col-sm-2">
<label for="projSummary">Project Summary: </label>
</div>
<div class="col-sm-10">
<textarea class="form-control" id="projSummary" required ng-model="itm.projSummary" rows="3"></textarea>
</div>
</div>
</form>
<div class="form-row text-center">
<div class="col-12">
<button ng-disabled="kfgPmForm.$invalid" ng-click="update(itm)" class="btn btn-info">SUBMIT</button>
<div><br></div>
</form>
<div><br></div>
<div class="col-sm-12" class="form-horizontal">
<label for="search" class="col-sm-3 col-form-label">Search: </label>
<div class="col-sm-6">
<input ng-model="searchText" class="form-control" ng-keyup="filterFunc()">
<div><br></div>
</div>
</div>
<div class="results">
<table class="table table-bordered table-responsive-md table-striped text-center">
<thead class="thead-light">
<tr>
<th>Project ID</th>
<th>Project Name</th>
<th>Project Owner</th>
<th>Key Stakeholders</th>
<th>Prepared By</th>
<th>Requested Date</th>
<th>Status</th>
<th>Department</th>
<th>Project Summary</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="itm in master | filter: itm.search">
<td><span ng-hide="editMode">{{itm.projectID}}</span>
<input type="text" ng-show="editMode" ng-model="itm.projectID" />
</td>
<td><span ng-hide="editMode">{{itm.projectName}}</span>
<input type="text" ng-show="editMode" ng-model="itm.projectName" />
</td>
<td><span ng-hide="editMode">{{itm.projectOwner}}</span>
<input type="text" ng-show="editMode" ng-model="itm.projectOwner" />
</td>
<td><span ng-hide="editMode">{{itm.keyStake}}</span>
<input type="text" ng-show="editMode" ng-model="itm.keyStake" />
</td>
<td><span ng-hide="editMode">{{itm.prepBy}}</span>
<input type="text" ng-show="editMode" ng-model="itm.prepBy" />
</td>
<td><span ng-hide="editMode">{{itm.reqDate}}</span>
<input type="text" ng-show="editMode" ng-model="itm.reqDate" />
</td>
<td><span ng-hide="editMode">{{itm.status.option}}</span>
<input type="text" ng-show="editMode" ng-model="itm.status" />
</td>
<td><span ng-hide="editMode">{{itm.dept}}</span>
<input type="text" ng-show="editMode" ng-model="itm.dept" />
</td>
<td><span ng-hide="editMode">{{itm.projSummary}}</span>
<input type="text" ng-show="editMode" ng-model="itm.projSummary" />
</td>
<td>
<button ng-click="EditProject(itm)" class="btn btn-primary">Edit</button>
<button ng-hide="editMode" ng-click="removeItem($index)" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<br>
</div>
</body>
</html>
This is my app.js file:
var isHtml5Compatible = document.createElement('canvas').getContext != undefined;
if (isHtml5Compatible) {
initiateLocalStorage();
}
function initiateLocalStorage() {
var app = angular.module('kfgPm', ['storageService']);
app.controller('MainCtrl', ['$scope', 'getLocalStorage', function($scope, getLocalStorage) {
$scope.EditProject = EditProject;
$scope.master = getLocalStorage.getData();
$scope.master = [];
$scope.update = function() {
var IsNew = true; //if the data entered in the field is new
angular.forEach($scope.master, function(LItem, key) {
if (LItem.projectID == $scope.itm.projectID) { //if the new project ID equals old project ID
IsNew = false; //data entered is to be edited
LItem.projectID = $scope.itm.projectID;
LItem.projectName = $scope.itm.projectName;
LItem.projectOwner = $scope.itm.projectOwner;
LItem.keyStake = $scope.itm.keyStake;
LItem.prepBy = $scope.itm.prepBy;
LItem.reqDate = $scope.itm.reqDate;
LItem.status = $scope.itm.status;
LItem.dept = $scope.itm.dept;
LItem.projSummary = $scope.itm.projSummary;
}
});
if (IsNew) { //if new data
$scope.master.push({ //add to the fields
'projectID': $scope.itm.projectID,
'projectName': $scope.itm.projectName,
'projectOwner': $scope.itm.projectOwner,
'keyStake': $scope.itm.keyStake,
'prepBy': $scope.itm.prepBy,
'reqDate': $scope.itm.reqDate,
'status': $scope.itm.status,
'dept': $scope.itm.dept,
'projSummary': $scope.itm.projSummary,
});
}
getLocalStorage.update($scope.master);
$scope.itm.projectID = '';
$scope.itm.projectName = '';
$scope.itm.projectOwner = '';
$scope.itm.keyStake = '';
$scope.itm.prepBy = '';
$scope.itm.reqDate = '';
$scope.itm.status = '';
$scope.itm.dept = '';
$scope.itm.projSummary = '';
},
$scope.removeItem = function(index) {
console.log(index);
$scope.master.splice(index, 1)
getLocalStorage.update($scope.master);
},
$scope.editItem = function(index) {
getLocalStorage.update($scope.master);
$scope.editing = $scope.master.indexOf(index);
}
function EditProject(pItem) { //if edit is clicked the data is replaced in respective fields
$scope.itm.projectID = pItem.projectID;
$scope.itm.projectName = pItem.projectName;
$scope.itm.projectOwner = pItem.projectOwner;
$scope.itm.keyStake = pItem.keyStake;
$scope.itm.prepBy = pItem.prepBy;
$scope.itm.reqDate = pItem.reqDate;
$scope.itm.status = pItem.status;
$scope.itm.dept = pItem.dept;
$scope.itm.projSummary = pItem.projSummary;
console.log(pItem);
}
$scope.arrlist = [{
"id": 1,
"option": "One"
}, {
"id": 2,
"option": "Two"
}];
$scope.userselected = $scope.arrlist[1];
$scope.LItem = angular.copy($scope.update);
$scope.filterFunc = function() {
$scope.LItem = $filter('filter')($scope.update, { $: $scope.searchText });
}
$scope.submitForm = function(isValid) {
if (isValid) {
alert('Submitted Successfully');
}
};
}]);
}
I am trying to implement the search for all columns such that when I type something in the search text field, it should return only the row with those searched terms and the rest of the rows would be hidden in the table.
To start, I see the following problems:
<body ng-app="kfgPm">
<div ng-controller="MainCtrl" class="container">
<form name="kfgPmForm" ng-submit="submitForm(kfgPmForm.$valid)" novalidate>
<!-- duplicate class attribute -->
<div class="col-sm-12" class="form-horizontal" role="form">
<!-- end tag seen too early -->
</div>
</div>
Duplicate class attribute -- the second one will be ignored
End tag seen too early - the scope of the controller will be limited
These two errors alone will cause the app to fail.
Also angular.js and bootstrap.js do not play well together. They do not co-ordinate their manipulation of the DOM.
I got a problem with my validation of textboxes.
I am trying to get something like this.
Click on the button, give a message when something is not filled in, while you fill the empty textbox, the 1 message of that textbox should dissapear.
If you click the button again, with 1 empty textbox, only the message of that textbox should appear.
If you click it twice with nothing filled, it should only appear once ...
I messed something up here ...
can someone get me on again?
Thank you in advance!
var list2 = [];
function valideer(el) {
divOutput = document.getElementById("msgbox1");
var strValideer = "<ul>";
if (document.getElementById("naam").value === "") {
list2.push("naam");
} if (document.getElementById("voornaam").value === "") {
list2.push("voornaam");
} if (document.getElementById("straatnr").value === "") {
list2.push("straatnr");
} if (document.getElementById("postgem").selectedIndex === 0) {
list2.push("postgem");
} if (document.getElementById("telgsm").value === "") {
list2.push("telgsm");
} if (document.getElementById("email").value === "") {
list2.push("email");
}
for (var i = 0; i < list2.length; i++) {
strValideer += "<li><b>" + list2[i] + ": </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
function inputChange(el) {
divOutput = document.getElementById("msgbox1");
strValideer = "<ul>";
var naam = document.getElementById("naam").value;
if (naam !== "") {
list2.splice(list2.indexOf(el.name), 1);
}
for (var i = 0; i < list2.length; i++) {
strValideer += "<li><b>" + list2[i] + ": </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="bootstrap/css/bootstrap_custom.min.css" type="text/css" rel="stylesheet" />
<!--lay-out met bootstrap grid-->
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="woodfactory.js" type="text/javascript"></script>
</head>
<body>
<section class="container" id="userform">
<form action="js_form_ontvanger.html" method="get" class="form-horizontal" name="frmUserform" id="frmUserform" onsubmit="return validate(this)" oninput="inputChange(this)">
<fieldset>
<legend>Persoonlijke gegevens</legend>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<label class="control-label" for="naam">naam:</label>
<div class="controls">
<input type="text" id="naam" name="naam" placeholder="naam" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="voornaam">voornaam:</label>
<div class="controls">
<input type="text" id="voornaam" name="voornaam" placeholder="voornaam" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="straatnr">straat+nr:</label>
<div class="controls">
<input type="text" id="straatnr" name="straatnr" placeholder="straat+nr" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="postgem">post+gem:</label>
<div class="controls">
<select id="postgem" required onsubmit="valideer(this)" onclick="inputChange(this)">
<option value="">-- maak een keuze --</option>
<option value="2000">2000 Antwerpen</option>
<option value="9000">9000 Gent</option>
<option value="9300">9300 Aalst</option>
<option value="9400">9400 Ninove</option>
<option value="9450">9450 Haaltert</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="telgsm">tel/gsm:</label>
<div class="controls">
<input type="text" id="telgsm" name="telgsm" placeholder="tel/gsm" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="e-mail" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<!--einde span7-->
</div>
<div class="span4 valid">
<div id="msgbox1" class="alert alert-error">
<div class="span1">
</div>
</div>
</div>
<div class="span1">
<div class="span1">
</div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</div>
</fieldset>
<fieldset>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success" onclick="valideer(this)">Verzenden</button>
</div>
</div>
<div class="span4 valid">
<div id="msgbox3" class="alert alert-success"></div>
</div>
<div class="span1"><!--lege kolom--></div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</fieldset>
</form>
</section>
<footer class="container">
<p>© 2013 The Wood Factory </p>
</footer>
</body>
</html>
I feel like your approach is a little more complicated than it needs to be.. See my attempt below
function valideer(current) {
var ids = ['naam', 'voornaam', 'straatnr', 'postgem', 'telgsm', 'email'];
var str = '<ul>';
ids.forEach(function(id) {
var el = document.getElementById(id);
if (el.value === '' && el !== current) {
str += "<li><b>" + id + ": </b>verplicht veld</li>";
}
});
str += '</ul>';
var outputDiv = document.getElementById("msgbox1");
outputDiv.innerHTML = str;
}
function handleFormSubmit(ev) {
ev.preventDefault();
valideer();
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="bootstrap/css/bootstrap_custom.min.css" type="text/css" rel="stylesheet" />
<!--lay-out met bootstrap grid-->
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="woodfactory.js" type="text/javascript"></script>
</head>
<body>
<section class="container" id="userform">
<form action="js_form_ontvanger.html" method="get" class="form-horizontal" name="frmUserform" id="frmUserform" onsubmit="handleFormSubmit">
<fieldset>
<legend>Persoonlijke gegevens</legend>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<label class="control-label" for="naam">naam:</label>
<div class="controls">
<input type="text" id="naam" name="naam" placeholder="naam" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="voornaam">voornaam:</label>
<div class="controls">
<input type="text" id="voornaam" name="voornaam" placeholder="voornaam" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="straatnr">straat+nr:</label>
<div class="controls">
<input type="text" id="straatnr" name="straatnr" placeholder="straat+nr" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="postgem">post+gem:</label>
<div class="controls">
<select id="postgem" required onclick="valideer(this)">
<option value="">-- maak een keuze --</option>
<option value="2000">2000 Antwerpen</option>
<option value="9000">9000 Gent</option>
<option value="9300">9300 Aalst</option>
<option value="9400">9400 Ninove</option>
<option value="9450">9450 Haaltert</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="telgsm">tel/gsm:</label>
<div class="controls">
<input type="text" id="telgsm" name="telgsm" placeholder="tel/gsm" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="e-mail" required onclick="valideer(this)">
</div>
</div>
<!--einde span7-->
</div>
<div class="span4 valid">
<div id="msgbox1" class="alert alert-error">
<div class="span1">
</div>
</div>
</div>
<div class="span1">
<div class="span1">
</div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</div>
</fieldset>
<fieldset>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success" onclick="valideer(this)">Verzenden</button>
</div>
</div>
<div class="span4 valid">
<div id="msgbox3" class="alert alert-success"></div>
</div>
<div class="span1">
<!--lege kolom-->
</div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</fieldset>
</form>
</section>
<footer class="container">
<p>© 2013 The Wood Factory </p>
</footer>
</body>
</html>
Some notes and observations:
Since the only check being used for validation is if it contains, an empty string, I have generalised the valideer function to iterate and operate on a given array of ids. This can be made even better by querying for inputs on your form using a DOM query and handling it like that.
You have added a lot of inline event handlers in your dom.. Some of them are redundant and not really needed. For example, having a simgle onsubmit on your form element should suffice (no need to add it for every input inside the form)
You were using a global variable list2 this is what was causing the repeated entries each time you click the button. Localising the scope would fix that (by moving it inside a function)
You're already using required property, which means you no longer need a js function to validate if your inputs are empty or not.
You should also notice that list2 is a global variable, which means that you should clean it at the end of every valideer() invocation.
All in all, you code seems very verbose .. try to find a better way to express you needs.
I need some help, I'm really stuck with this problem, I have this javascript code, which adds new rows to my DataTable onClick:
<script type="text/javascript">
function deleteRow(o){
var p=o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
findTotal();
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
var enter_value = Number(arr[i].textContent)
if(enter_value)
tot += Number(arr[i].textContent);
}
document.getElementById('total').value = tot;
}
</script>
<td>s are gerated as expected. As you can see in the this picture on the browsers developer tool.
How would I save these tds to python?
Here's a bit of my HTML:
<div class="jumbotron jumbotron-sm">
<div class="container" id = "contact">
<div class="row">
<div class="col-sm-12 col-lg-12">
<h1 class="h1">
Accountable Form 51 <small>Made easier</small></h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12" style="display: inline-block;">
<div class="well well-sm">
<form action="{{ url_for('addrec') }}" method=post>
<div class="row">
<div class="col-md-6" style="display: inline-block; ">
<div class="form-group">
<label for="name">
O.R Number</label>
<br>
<span class="glyphicon glyphicon-user-list-alt"><input type="hidden" name="OR" value="{{receiptno}}">
<br>
<h1>#{{receiptno}}</h1></span><br>
</div>
<br>
<br>
<div class="form-group">
<label for="email">
Payor</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span>
</span>
<input type="text" class="form-control" name = "payor" id="payor" placeholder="Enter Full Name" required="required" /></div>
</div>
<div class="form-group">
<label for="subject">
Nature of Payment</label>
<div id="RadioGroup">
<br>
<input type="radio" name="paymentmethod" checked="checked" value="CASH"> Cash<br>
<input type="radio" name="paymentmethod" value="CHECK"> Check<br>
<div id="PaymentsCHECK" class="desc" style="display: none;">
<br>
Drawee Bank<br><input type="text" name="dbank"><br>
Account No.<br><input type="text" name="dNum"><br>
Date Issued<br><input type="text" name="dDate"><br>
Account Name<br><input type="text" name="dName"><br>
</div>
<input type="radio" name="paymentmethod" value="MONEY"> Money Order<br>
<div id="PaymentsMONEY" class="desc" style="display: none;">
<br>
Money Order No.<br><input type="text" name="dbank">
</div>
</div>
</div> <!-- FORM GROUP END -->
<div class="form-group">
<label for="name">
Memo</label>
<textarea name="message" id="message" class="form-control" rows="5" cols="25" required="required"
placeholder="Message"></textarea>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary pull-right" id="btnContactUs">
Submit Form</button>
<br>
</div>
</div>
</div><!-- FIRST COL6 END -->
</div><br><br><br><br><!-- ROW END -->
</form>
<form>
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form name="noc">
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<datalist id="languages">
{% for row in rows %}
<option value = "{{row[0]}}">
{% endfor %}
</datalist>
</div> <!-- JUMBO END -->
<h6> <label>Date:<span></span>
</label> {{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<h2>₱<input type = "text" name = "total" id="total"></h2>
</fieldset></h3>
</div><!-- COL5 END -->
<!-- </div> --><!-- REMAIN OR NOT? DEPENDS ON DEBUG PROCESS LATER -->
<div class="col-md-6" style="display: inline-block;">
<div class="jumbotron">
<h2>Nature of Collection</h2>
</div>
<div>
<!-- ACCUMULATION TABLE STARTS -->
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<!-- </form> --> <!-- CHECK LATER -->
<datalist id="languages">
{% for row in rows %}
<option value={{row[0]}}></option>
{% endfor %}
</datalist>
</div>
</form>
</div>
</div>
</div>
</div>
and my full Python code which is suppsoed to receive the input in this problem:
#app.route('/addrec',methods = ['POST', 'GET'])
def addrec():
if g.user:
if request.method == 'POST':
#UPPER PANE
payor = request.form['payor']
receiptno = request.form['OR']
paymentmethod = request.form['paymentmethod']
naive_dt = time.strftime("%m/%d/%Y")
collectiondate = naive_dt = datetime.now()
message = request.form['message']
#LOWER PANE
url_to_scrape = 'http://localhost:5000/form'
r = requests.get(url_to_scrape)
soup = BeautifulSoup(r.text)
nature = []
for table_row in soup.select("table.inmatesList tr"):
cells = table_row.findAll('td')
if len(cells) > 0:
nature = cells[0].text.strip()
natureamt = cells[1].text.strip()
nature = {'nature': nature, 'nature': natureamt}
nature_list.append(nature)
ent = Entry(receiptno, payor,officer, paymentmethod, collectiondate,message, nature_list)
add_entry(ent)
actions="Applied"
return redirect(url_for('form'))
return redirect(url_for('home'))
As you can see I already tried scraping but it just loads forever. Is there any way I can get this? I separated my HTML into 2 parts. UPPER PANE and LOWER PANE. UPPER pane gets input for the basic input does and the LOWER PANE has a table and its cells are generated by an oNClick function.
So why did I separate it into two forms? This is because it gets complicated for the Lower Pane. For example, I click ADD ENTRY, instead of adding an entry its just reloads the whole website and nothing happens.
If you have an easier/cleaner/better way to do this other than scraping please do help.
//here we crate the module for the CRUD application here
var app= angular.module("myApp",[]);
app.controller("myCont", function($scope,myService){
$scope.user =[];
$scope.one = [];
//here we create the myService function for show the Dmmt array
$scope.user = myService.show();
console.log($scope.user);
//here we create the saveUser function for push the item into the list
$scope.saveUser = function(){
var data =
{
eid:$scope.user.eid,
email:$scope.user.email,
city:$scope.user.city,
salary:$scope.user.salary,
date:$scope.user.date,
}
console.log(data);
//here we create will pass the user data to the myService of the show2
$scope.user =myService.show2(data);
//Here we clear the form data with the help of the id
document.getElementById("clear").reset();
//Here we clear the form data without function
// $scope.user.eid ="";
// $scope.user.email ="";
// $scope.user.city ="";
// $scope.user.salary ="";
// $scope.user.date ="";*/
}
//Calling setParam function for the particular userDetails.
$scope.setParam = function(index){
$scope.one = $scope.user[index];
console.log($scope.one);
}
//here we delete the deleteUser function for remove the item into the lsit
$scope.deleteUser = function(index) {
$scope.result3 =myService.show3(index);
console.log($scope.result3);
}//close contrller here
$scope.clearFilter =function() {
$scope.user= "";
}
});
//Declare the services
//her e we crete the myService function in which we declare the static that will be display in the
//index.html page
app.service("myService",function(){
var employee =[];
var message="";
//here we create the show function for declare dynamic array & display in the home page of the user
this.show = function(){
employee =
[
{
eid:"Kapil sssssss",
email:"harry#yahoo.com",
salary:12000,
city:"Indore",
date:"2014-10-19",
img:"./images/download.png"
},
{
eid:"pooooo",
email:"harry#yahoo.com",
salary:5000,
city:"Us",
date:"2014-10-28",
img:"../images/user.jpg"
},
{
eid:"ddsa",
email:"harry#yahoo.com",
salary:120,
city:"Bhopal",
date:"2014-10-24",
img:"./images/avtar.jpg"
},
{
eid:"dsaddaPotter",
email:"harry#yahoo.com",
salary:1000,
city:"Agar-malwa",
date:"2014-10-29",
img:"./images/images.jpg"
},
{
eid:"sadadasdasdasdsadsads54454",
email:"harry#yahoo.com",
salary:25000,
city:"Indore",
date:"2014-10-10",
img:"./images/WP_16 September 2015_qstore.jpg"
},
{
eid:"Gotm Potter",
email:"harry#yahoo.com",
salary:2000,
city:"Playboy",
date:"2014-10-03",
img:"./images/download (1).png"
},
{
eid:"Harry a4644464654s Potter",
email:"harry#yahoo.com",
salary:35000,
city:"Agar",
date:"2014-10-19",
img:"./images/download.png"
},
{
eid:"mMayank rawal",
email:"harry#yahoo.com",
salary:5000,
city:"Ujjain",
date:"2014-10-28",
img:"../images/user.jpg"
},
{
eid:"Gotm Soni",
email:"gotm#yahoo.com",
salary:2000,
city:"Dewas",
date:"2014-10-24",
img:"./images/avtar.jpg"
},
{
eid:"Deepsh thakur",
email:"harry#yahoo.com",
salary:12000,
city:"Australia",
date:"2014-10-29",
img:"./images/images.jpg"
},
{
eid:"Peter Potter",
email:"harry#yahoo.com",
salary:5000,
city:"Harmaini",
date:"2014-10-10",
img:"./images/WP_16 September 2015_qstore.jpg"
},
{
eid:"kapil Soni",
email:"kapil#yahoo.com",
salary:2000,
city:"Playboy",
date:"2014-10-03",
img:"./images/download (1).png"
}
]
return employee;
}
//here we create the show2 function that will be received our data from the contoller
//& the push into the array of the employee
this.show2 = function(data){
employee.push(data);
message="push ho gy";
return employee;
}
//here we create the show3 function that will be remove user from the list
//& through the index of the list
this.show3 = function(index){
employee.splice(index,1); }
}
);
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="custom.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- include the angularjs files here-->
<script src="angular.min.js"></script>
<script src="jquery-1.12.4.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap.min.js"></script>
<script src="app/controller.js"></script>
<script src="app/service.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
individual files as needed -->
</head>
<body ng-controller="myCont">
<div class="jumbotron">
<div class="container">
<button type="button" class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#myModal">Add New User</button>
<input type="checkbox" data-ng-model='ok.type1' data-ng-true-value="'Bhopal'" data-ng-false-value=''/>Bhopal
<br>
<input type="checkbox" data-ng-model='ok.type2' data-ng-true-value="'Indore'" data-ng-false-value=''/> Indore<br>
<input type="checkbox" data-ng-model='ok.type3' data-ng-true-value="'Ujjain'" data-ng-false-value=''/>Ujjain
<br>
<input type="checkbox" data-ng-model='ok.type4' data-ng-true-value="'London'" data-ng-false-value=''/>London<br>
<select ng-model="search">
<option value="Bhopal">Bhopal</option>
<option value="London">London</option>
<option value="Australia">Australia</option>
</select>
<button class="btn btn-succes btn-md pull-right" id="clear-filter" ng-click="clearFilter()" type="button">Clear Filter</button>
<a href="#"><i class="fa fa-heart" aria-hidden="true"></i>
<div class="input-group">
<input type="text" class="form-control" ng-model="search" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
<div class="alert alert-info" ng-if="message">
Info×.
</div>
<table class="table table-hover">
<thead>
<tr>
<th>User</th>
<th>EmployeenName</th>
<th>Email</th>
<th>Salary</th>
<th>City</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in filtered =(user | filter:search) | filter:ok.type1 | filter:ok.type2 | filter:ok.type3 | filter:ok.type4 | orderBy:'salary' "
onclick="document.getElementById('id01').style.display='block'"
ng-click ="setParam($index)">
<td style="max-height:61px;"><img src={{x.img}}></img></td>
<td>{{x.eid}}</td>
<td>{{x.email}} </td>
<td>{{x.salary| currency}}</td>
<td>{{x.city}}</td>
<td>{{x.date | date:'dd/mm/yy'}}</td>
<div style="float:right; margin-top:8px;">
Total Count after Filtered-{{filtered.length}}</p>
</div>
<td>
<button type="button" class="btn btn-info" ng-click="isEditForm=true;">edit</button>
</td>
<td ng-show="isEditForm">
<lable>Name</label><input ng-model="x.eid"/><br>
<lable>Email</label><input ng-model="x.email"/><br>
<lable>salary</label><input ng-model="x.salary"/><br>
<lable>city</label><input ng-model="x.city"/><br>
<lable>date</label><input ng-model="x.date"/><br>
<button ng-click="isEditForm=false;">SAVE HERE</button>
</td>
<td>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Modal -->
//here we will provide the id for clear data
<form name="newUser" id="clear" class="user" class="form-horizontal">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class ="UpperText" class="modal-title" >New User Registration</h4>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="eid" ng-model="user.eid" placeholder="Enter Name" ng-minlength ="3" ng-maxlength="5">
<span class="danger" ng-show="newUser.eid.$touched && newUser.eid.$pristine" class="help-block">Enter EId</span>
<span class="danger" ng-show="newUser.eid.$error.minlength" class="help-block">Enter min 3 digits.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Email</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Enter Email" required>
<span class="danger" ng-show="newUser.email.$touched && newUser.email.$pristine" class="help-block">Enter Email</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" style="white-space: nowrap;">Select Country:</label>
<div class="col-sm-10">
<select class="form-control countries" ng-model="user.city" id="countryId sel1">
<option value="">Select City</option>
<option value="Indore">Indore</option>
<option value="Bhopal">Bhopal</option>
<option value="Ujjain">Ujjain</option>
</select>
</div>
<!-- <div class="form-group">
<label class="control-label col-sm-2">City</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="city" ng-model="user.city" placeholder="Enter city">
<span class="danger" ng-show="newUser.city.$touched && newUser.city.$pristine" class="help-block">
<span>Enter City</span>
</div>
</div> -->
<div class="form-group">
<label class="control-label col-sm-2">Salary</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="salary" ng-model="user.salary" placeholder="Enter salary">
<span class="danger" ng-show="newUser.salary.$touched && newUser.salary.$pristine" class="help-block">Enter Salary</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="date" ng-model="user.date" placeholder="Enter date">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-default" data-dismiss="modal"
ng-click="saveUser()" ng-disabled="newUser.$invalid" >
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div> <!-- here model body is closed-->
</div> <!-- here model content is clo sed-->
</form>
<!-- Declare another model is declare for edit Modal -->
<!--Here we creat the delete user model for dlete the user -->
<div class="modal fade" id="myModalDelete" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×
</button>
<h4 class="modal-title">Are R Want to Delete </h4>
</div>
<div class="modal-body">
<strong style="color:blue;">
You re going to delete the {{one.eid}}</strong>
</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="deleteUser($index)">Yes
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
</div>
</div> <!-- here model body is closed-->
</div> <!-- here model content is closed-->
</div>
<div class="w3-container">
<div id="id01" class="w3-modal">
<div class="w3-modal-content w3-card-8 w3-animate-left" style="max-width:600px">
<div class="w3-center"><br>
<span onclick="document.getElementById('id01').style.display='none'" class="w3-closebtn w3-hover-red w3-container w3-padding-8 w3-display-topright" title="Close Modal">×</span>
<img src="{{one.img}}" alt="Avatar" class="w3-circle w3-margin-top">
</div>
<form class="w3-container" action="form.asp">
<div class="table-responsive">
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Email</th>
<th>Salary</th>
<th>City</th>
<th>Date</th>
</tr>
<tr>
<td>{{one.eid}}</td>
<td>{{one.email}}</td>
<td>{{one.salary}}</td>
<td>{{one.city}}</td>
<td>{{one.date}}</td>
<span class="btn btn-info">Follow Here</span>
</table>
</div>
</form>
</div>
</div>
</div>
</body>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) --
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</html>
I have to apply the filter with checkbox in such case checkbox filter is working properly and list is properly filtered but after that i have click on the Reset button to reset all the JSON data but in my case all data is cleared how to do this functionality.
You need to create a deep copy of your data and then on hitting reset reassign it.
angular.copy(source, [destination]);