Javascript in HTML forms, Accumulating Total Realtime - javascript

I have a bit of a problem with my HTML and JAVASCRIPT Combination.
I'm trying to create a page where I am able to add values by a certain parameter. It's it in this picture of how it would work.
The whole page:
Here's my code to this overall HTML Page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Naawan Receipt System</title>
<link rel="stylesheet" href="static/header-second-bar.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>
</head>
<body>
<header class="header-two-bars">
<div class="header-first-bar">
<div class="header-limiter">
<h1>Municipality<span>Receipt</span></h1>
<nav>
FORM
LOGS
QUERY
USER
</nav>
Logout
</div>
</div>
<div class="header-second-bar">
<div class="header-limiter">
<h2>User: {{ user }}</h2>
<nav>
<i class="fa fa-comments-o"></i> Nature of Collection
<i class="fa fa-file-text"></i> Results
<i class="fa fa-group"></i> Participants
<i class="fa fa-cogs"></i> Settings
</nav>
</div>
</div>
</header>
<!-- CONTENT HERE. -->
<link rel="stylesheet" href="static/indextest.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="static/indextest.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>
<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>
<div class="row">
<div class="col-md-6" style="display: inline-block; ">
<div class="form-group">
<label for="name">
O.R Number</label>
<input type="text" class="form-control" id="name" placeholder="Enter O.R Number" required="required" />
</div>
<div class="form-group">
<label for="email">
Payor</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></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<input type="text" name="dbank">
Number<input type="text" name="dNum">
Date<input type="text" name="dDate">
</div>
<input type="radio" name="paymentmethod" value="MONEY"> Money Order<br>
<div id="PaymentsMONEY" class="desc" style="display: none;">
<br>
<input type="text" name="dbank">Money Order No.
</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><!-- FIRST COL6 END -->
</div><br><br><br><br><!-- ROW END -->
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<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>
<input type = "text" name = "total" id="total"><br></p>
</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%">
<tr>
</tr>
<tbody>
</tbody>
</table>
<!-- </form> --> <!-- CHECK LATER -->
<datalist id="languages">
{% for row in rows %}
<option value={{row[0]}}></option>
{% endfor %}
</datalist>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary pull-right" id="btnContactUs">
Submit Form</button>
<br>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
/*EDIT HERE LATER*/
$(document).ready(function() {
$("input[name$='paymentmethod']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#Payments" + test).show();
});
});
</script>
<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;
}
</script>
<script type="text/javascript">
function findTotal(){
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
</body>
</html>
So I am done in that part, this time I wanted to add the values of each amount added and display it real-time on the Total inputbox. So I put an id to the cell which the amounts will be generate in the javascript:
Before:
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;
}
After:
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;
cell2.id = "qty
cell3.innerHTML = delete1;
}
"qty" here will match the ID's of all entry on cell 2 and will add it and will display it on the id total.
But when I do this the value box at the top side pops out an error:
It prompts me to enter a value on the unrelated boxes.
I also tried separating them by forms but it didn't work.
I tried this on the other forms I have and its working, I was just using a checkbox plus textbox, however on this page I am unable to do it. What should I do on this case?
A checklist just to be clear:
I generated ID's for each cell added
I used that ID to evaluate on a javascript script
The accumulated total was supposed to go to the ID "total" but it didn't happen.
I already tried separating the forms, but this time it only reloaded and the entries weren't added.
I have a separate button for saving all fields named "Submit Form"
Any input or ways how to do this in your opinion?

The reason you're getting this error is due to nested forms, which are not a constructed supported by browsers. Make sure you close your first form before starting the new one - then validation won't cross-contaminate.
To be clear, this has nothing to do with the way you're totalling your values (though that has some issues to be resolved on its own, e.g. you're accessing the value of your elements, while you've never set it - instead you want to be getting their innerHtml).

Related

Displaying user input in the table form using Javascript DOM

i have trouble displaying users' input and have spent some time looking at it and unsure which part had gone wrong. I am supposed to display the "Result" word in green and display user's input in a form of table. I used document.getElementsByClassName('container').innerHTML to add new element in the homepage.
Could anyone explain why the word Result and table doesn't show?
My code:
/*** Home ***/
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="mhsavings.js"></script>
</head>
<style>
.main-content{
width:70%;
/* background-color: lightblue; */
text-align: center;
}
</style>
<body>
<div class="container main-content">
<h1 style="margin-top:40px; margin-bottom: 30px;">Savings</h1>
<h3 style="color:blue;margin-bottom:48px;">How long does it takes for me to reach My Goal?</h3>
<form>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon1">Initial Amount ($)</span>
<input type="text" class="form-control" placeholder="" aria-label="initial Amt" aria-describedby="basic-addon1" id="initialAmt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon2">Yearly interest (%)</span>
<input type="text" class="form-control" aria-label="yearly interest" aria-describedby="basic-addon2" id="yearlyInt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon3">My Goal</span>
<input type="text" class="form-control" id="goal" aria-describedby="basic-addon3" id="goal">
</div>
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
</form>
</div>
</body>
</html>
/*** in JS file ***/
function calculate(){
'use stict';
var initialAmt = document.getElementById("initialAmt");
var yearlyInt = document.getElementById("yearlyInt");
var goal = document.getElementById("goal");
console.log(goal.value);
var receive = Math.round(initialAmt, 2);
var years = 0;
while (receive < goal) {
receive *= (1 + yearlyInt);
years += 1;
}
// console.log(document.getElementsByClassName('container'));
document.getElementsByClassName('container').innerHTML = "<h3 style='color:green; margin-bottom: 20px'>Result</h3>";
document.getElementsByClassName('container').innerHTML = `<table style='width: 500px'>
<tr>
<th>You will achieve your goal in (years):</th>
<td>${years}</td>
</tr>
<tr>
<th>You will get ($):</th>
<td>${receive}</td>
</tr>
</table>`;
}
#1: name of function not the function execution!
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
to
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate">Calculate</button>
#2: getElementsByClassName returns a collection not an element!
#3: lacking of parseInt before calculating
Beside the comments from other user posted in your original question,you code has many incorrect points:
You need to use value to get the input value,so change var initialAmt = document.getElementById("initialAmt"); to var initialAmt = document.getElementById("initialAmt").value;
When use innerHTML,you need to append the value,make sure not to override it
function calculate(){
'use stict';
var initialAmt = parseInt(document.getElementById("initialAmt").value);
var yearlyInt = parseInt(document.getElementById("yearlyInt").value);
var goal = parseInt(document.getElementById("goal").value);
var receive = Math.round(initialAmt, 2);
var years = 0;
while (receive < goal) {
receive *= (1 + yearlyInt);
years += 1;
}
// console.log(document.getElementsByClassName('container'));
var result = document.createElement("div");
var content = "<h3 style='color:green; margin-bottom: 20px'>Result</h3>";
content += `<table style='width: 500px;border:1px'>
<tr>
<th>You will achieve your goal in (years):</th>
<td>`+years+`</td>
</tr>
<tr>
<th>You will get ($):</th>
<td>`+receive+`</td>
</tr>
</table>`;
result.innerHTML = content;
document.getElementsByClassName('container')[0].appendChild(result);
}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="mhsavings.js"></script>
</head>
<style>
.main-content{
width:70%;
/* background-color: lightblue; */
text-align: center;
}
</style>
<body>
<div class="container main-content">
<h1 style="margin-top:40px; margin-bottom: 30px;">Savings</h1>
<h3 style="color:blue;margin-bottom:48px;">How long does it takes for me to reach My Goal?</h3>
<form>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon1">Initial Amount ($)</span>
<input type="text" class="form-control" placeholder="" aria-label="initial Amt" aria-describedby="basic-addon1" id="initialAmt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon2">Yearly interest (%)</span>
<input type="text" class="form-control" aria-label="yearly interest" aria-describedby="basic-addon2" id="yearlyInt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon3">My Goal</span>
<input type="text" class="form-control" id="goal" aria-describedby="basic-addon3" id="goal">
</div>
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
</form>
</div>
</body>
</html>
Using your functio, you may use this code
form fields are text fields. With parseInt() a text string is converted into an integer.
Below I added an extra <div id="result"></div> but if you want to use the container div, you can target this div with document.querySelector(".container").innerHTML = .... This will select the first class with that name. Note that this will replace all html code in the form!
function calculate(){
'use stict';
let initialAmt = parseInt( document.getElementById("initialAmt").value );
let yearlyInt = parseInt( document.getElementById("yearlyInt").value );
let goal = parseInt( document.getElementById("goal").value );
let receive = Math.round(initialAmt, 2);
let years = 0;
while (receive < goal) {
receive *= (1 + yearlyInt);
years += 1;
}
let result = '<h3 style="color:green; margin-bottom: 20px">Result</h3><table style="width: 500px"><tr><th>You will achieve your goal in (years):</th><td>' + years + '</td></tr><tr><th>You will get ($):</th><td>' + receive + '</td></tr></table>';
document.getElementById("result").innerHTML = result;
}
.main-content{
width:70%;
/* background-color: lightblue; */
text-align: center;
}
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div class="container main-content">
<h1 style="margin-top:40px; margin-bottom: 30px;">Savings</h1>
<h3 style="color:blue;margin-bottom:48px;">How long does it takes for me to reach My Goal?</h3>
<form>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon1">Initial Amount ($)</span>
<input type="text" class="form-control" placeholder="" aria-label="initial Amt" aria-describedby="basic-addon1" id="initialAmt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon2">Yearly interest (%)</span>
<input type="text" class="form-control" aria-label="yearly interest" aria-describedby="basic-addon2" id="yearlyInt">
</div>
<div class="input-group" style='margin-bottom: 16px;'>
<span class="input-group-text" id="basic-addon3">My Goal</span>
<input type="text" class="form-control" id="goal" aria-describedby="basic-addon3" id="goal">
</div>
<button type="button" class="btn btn-danger" style="margin-top:30px"; id="calc" onclick="calculate()">Calculate</button>
</form>
<div id="result"></div>
</div>

How can I add line break in userform?

I'm using "script app" from google sheets and I need to allow line break in the "userform" that I have created, I will use this to feed data to my google sheet and some of the items need multiple lines in the same cell.
Is there anyway I can do that?
EXAMPLE
EXAMPLE 2
CODE
function showAdicionarClienteHTML() {
var template = HtmlService.createTemplateFromFile("AdicionarClienteHTML");
var html = template.evaluate();
html.setTitle("ADICIONAR CLIENTE").setHeight(800).setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html, "Adicionar novo cliente:");
//.showModalDialog(html, "Adicionar novo cliente:");
//.showSidebar(html);
}
function appendData(data){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Clientes");
ws.appendRow([data.name,data.login,data.sninv,data.numero,data.sndtl,data.tele,data.regiao]);
}
HTML
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="nome" type="text" class="validate">
<label for="nome">Nome</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">mail_outline</i>
<input id="login" type="text" class="validate">
<label for="login">E-Mail ou Login</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">select_all</i>
<input id="sninv" type="text" class="validate">
<label for="sninv">S/N do Inversor</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">format_list_numberedl</i>
<input id="numero" type="text" class="validate">
<label for="numero">Numero do Inversor</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">select_all</i>
<input id="sndtl" type="text" class="validate">
<label for="sndtl">S/N do Datalogger</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">phone_in_talk</i>
<input id="tele" type="tel" class="validate">
<label for="tele">Telefone</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">explore</i>
<input id="regiao" type="text" class="validate">
<label for="regiao">Região</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" id="btn">Adicionar
<i class="material-icons right">send</i>
</button>
</div><!--END ROW -->
</div><!--END CONTAINER -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
var nameBox = document.getElementById("nome");
var loginBox = document.getElementById("login");
var sninvBox = document.getElementById("sninv");
var numeroBox = document.getElementById("numero");
var sndtlBox = document.getElementById("sndtl");
var teleBox = document.getElementById("tele");
var regiaoBox = document.getElementById("regiao");
document.getElementById("btn").addEventListener("click",addRecord);
function addRecord(){
var name = nameBox.value;
var login = loginBox.value;
var sninv = sninvBox.value;
var numero = numeroBox.value;
var sndtl = sndtlBox.value;
var tele = teleBox.value;
var regiao = regiaoBox.value;
if(name.trim().length == 0 || login.trim().length == 0 || sninv.trim().length == 0 || numero.trim().length == 0 || sndtl.trim().length == 0 || tele.trim().length == 0 || regiao.trim().length == 0){
//handle error
M.toast({html: 'Preencha todos os campos!'})
} else {
var data ={
name: nameBox.value,
login: loginBox.value,
sninv: sninvBox.value,
numero: numeroBox.value,
sndtl: sndtlBox.value,
tele: teleBox.value,
regiao: regiaoBox.value
};
google.script.run.appendData(data);
}//CLOSE ELSE
}//CLOSE ADD RECORD
</script>
</body>
</html>
The <input> tag doesn't support line breaks. If you want to add a multi-line input, you have to use <textarea> instead. So you should change all the elements which could potentially have several lines from <input> to <textarea>.
That is, you should change these lines:
<input id="sninv" type="text" class="validate">
<input id="numero" type="text" class="validate">
<input id="sndtl" type="text" class="validate">
To these ones:
<textarea id="sninv" type="text" class="validate"></textarea>
<textarea id="numero" type="text" class="validate"></textarea>
<textarea id="sndtl" type="text" class="validate"></textarea>
This way, you can add multi-line text, which will still be a multi-line when you send it to the spreadsheet.
Reference:
<textarea>
I hope this is of any help.

How to get Data from another page Local Storage?

``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";
}

Getting Javascript Generated Values to Flask

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.

showing a button if there are no dynamically created form fileds available

i have a field with 'add' and 'remove' field options and my problem is if someone click remove button at first time then there is nothing left. however i created a another button and hide it by this code.
$('#more_fields').hide();
is that possible to show this button when there is no field or no button with deleteMe class available
i'm using this code for delete fields.
$(document).on("click",".deleteMe", function(){
$(this).closest(".addform").remove();
});
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="addform"><div class="input-group"> <label for="Services">Services '+room+'</label> <input type="text" class="form-control" id="Services" name="serve[]" style="max-width: 148px;" placeholder="Add Services"> <span class="input-group-btn" > <button class="btn deleteMe" style="">×</button> <button class="btn btn-success pull-right" onclick="add_fields();" type="button"><i class="fa fa-plus"></i></button> </span> </div></div>';
objTo.appendChild(divtest)
}
//]]>
$(document).on("click",".deleteMe", function(){
$(this).closest(".addform").remove();
});
$('#more_fields').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="form-inline">
<div class="">
<div class="form-group">
<div id="room_fileds" class="text-center">
<div class="addform">
<!--<label for="qualification">Services 1</label>
<input type="text" class="form-control" id="Service" style="" placeholder="Add Services">
-->
<div class="input-group">
<label for="Services">Services 1</label>
<input type="text" class="form-control" id='Services' name="serve[]" style="max-width: 148px;" placeholder="Add Services">
<span class="input-group-btn" >
<button class="btn deleteMe" style="">×</button>
<button class="btn btn-success pull-right" onclick="add_fields();" type="button"><i class="fa fa-plus"></i></button>
</span>
</div>
<span id="err_quali" style="color:red;display:none;font-size:13px;padding-left:105px;">Enter only Chars</span>
</div>
</div>
<input type="button" class="btn btn-success btn-sm" id="more_fields" onclick="add_fields();" value="Add Services" />
</div>
</div>
</form>
on delete do like
room -= 1;
than if at some point you do
if(room===0) { /*here show your button */ }
I've noticed that you use ID for buttons like #err_quali, #Services... Don't. you're going to have load of duplicate IDs on the page which is wrong. Use classes instead.
jsBin demo
var rooms = 1;
var c = 1;
var $roomsWrapper = $("#room_fileds"); // the parent
var $room = $(".input-group").clone(); // Store a group
$('#more_fields').hide();
$(".form-inline").on("click", ".deleteMe", function(ev) {
ev.preventDefault();
rooms -= 1;
$(this).closest(".input-group").fadeOut(300, function(){
$(this).remove();
});
$('#more_fields').toggle( !rooms );
}).on("click", ".addField, #more_fields", function(ev) {
ev.preventDefault();
rooms += 1;
c += 1;
var $klon = $room.clone();
$klon.find(".groupNum").text(c);
$roomsWrapper.append( $klon );
});
.err_quali{
color:red;
display:none;
font-size:13px;
padding-left:105px;
}
.form-control{
max-width: 148px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- FORM -->
<form class="form-inline">
<div id="room_fileds">
<!-- CLONABLE FIELD HELPER -->
<div class="input-group">
<label for="Services">Services <span class="groupNum">1</span></label>
<input type="text" name="serve[]" placeholder="Add Service">
<span class="err_quali">Enter only Chars</span>
<span class="input-group-btn" >
<button class="deleteMe btn">×</button>
<button class="addField btn" type="button">+</button>
</span>
</div>
<!-- Here jQuery appends Room group clones -->
</div>
<button id="more_fields">Add Services</button>
</form>

Categories