Array items are not appending to the HTML Table tbody with jQuery - javascript

I have a table that is formatted and I want the contents of my array to be displayed in them, but nothing is displayed when I load my web page. It seems to not be adding anything to the tbody id that I have created in my html code. Here is my code that I have.
var Movie = function (movieTitle, movieYear, length, format, rating, favorite) {
this.movieTitle = movieTitle;
this.movieYear = movieYear;
this.length = length;
this.format = format;
this.rating = rating;
this.favorite = favorite;
};
var movies = new Array();
movies[0] = new Movie("Hangover", 2009, 210, "Dvd", 4, "Yes");
movies[1] = new Movie("Taken", 2008, 200, "BluRay", 5, "Yes");
movies[2] = new Movie("Avengers", 2011, 242, "Cloud", 3, "No");
movies[3] = new Movie("Iron Man", 2010, 311, "Computer", 4, "Yes");
movies[4] = new Movie("Rounders", 1990, 252, "Dvd", 5, "Yes");
movies[5] = new Movie("42", 2013, 202, "BluRay", 4, "No");
movies[6] = new Movie("Water Boy", 1988, 211, "Dvd", 5, "Yes");
movies[7] = new Movie("21", 2010, 192, "Cloud", 3, "No");
movies[8] = new Movie("I am Legend", 2009, "Computer", 5, "Yes");
movies[9] = new Movie("Titanic", 1997, 320, "Dvd", 2, "No");
$("#add").click(function(event){
var movie = new Movie(
$("#movieTitle").val(),
$("#movieYear").val(),
$("#lengthInMins").val(),
$("#formatSelections").val(),
$("#ratingSelections").val(),
$("#favoriteSelction").val()
);
movies[movies.length] = movie;
updateTableData();
$("#formMovieData").hide(500, function() {
$("#showMovies").show();
});
event.preventDefault(); // Prevents the defualt anchor actions
});
function updateTableData() {
//$("#movieData").empty();
var tbody = $("#movieData");
for (var i = 0; i < movies.length; i++) {
var id = i + "_" + movies[i]["movieTitle"];
var tr = "<tr>";
for (var key in movies[i]) {
tr += "<td>" + movies[i][key] + "</td>";
}
tr += "<td><a id='" + id + "' href='#'" + "> Edit </a></td>";
tr += "<td><a id='" + id + "' href='#'" + "> Delete </a></td>";
tr += "</tr>";
tbody.append(tr);
$("#" + id).click(function () {
var elementId = $(this).attr("id");
var idx = elementId.indexOf("_");
var index = parseInt(elementId.substr(0, idx));
$("#movieTitle").val(movies[index].movieTitle);
$("#movieYear").val(movies[index].movieYear);
$("#lengthInMins").val(movies[index].length);
$("#formatSelections").val(movies[index].format);
$("#ratingSelections").val(movies[index].rating);
$("#favoriteSelection").val(movies[index].favorite);
$("#showMovies").hide(500, function() {
$("#formMovieData").show();
});
});
}
}
Here is my html code I have hard coded some items that I want to show in my tables also I have the ability to add a new one as well. I am working on the process to add or delete the information as well, but I need to show items first.
<!DOCTYPE html>
<html>
<head>
<title>Homework 3</title>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<link href="../Content/StyleSheet.css" rel="stylesheet" />
<script src="../Scripts/jquery-2.1.0.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
</head>
<body>
<header><h1 class="bg-primary">The Movie Collection</h1></header>
<nav id="navigation" class="col-sm-3">
<ul class="nav navbar-default">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Movie Options
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a id="addMovieDataCmd" href="#">Add New Movies</a></li>
<li><a id="showMoviesCmd" href="#">Show All Movies</a></li>
<li><a id="browseNewMoviesCmd" href="http://www.fandango.com/new-dvd-releases">Browse New Release Movies</a></li>
</ul>
</li>
</ul>
</nav>
<div id="mainContent" class="col-sm-9">
<form id="formMovieData" class="form-horizontal">
<fieldset>
<legend>Add New Movie</legend>
<div class="form-group">
<label for="movieTitle" class="col-sm-1 control-label">Movie Title</label>
<div class="col-sm-offset-1 col-sm-5">
<input id="movieTitle" name="movieTitle" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="movieYear" class="col-sm-1 control-label">Year of Movie</label>
<div class="col-sm-offset-1 col-sm-5">
<input id="movieYear" name="movieYear" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="lengthInMins" class="col-sm-1 control-label">Length In Minutes</label>
<div class="col-sm-offset-1 col-sm-5">
<input id="lengthInMins" name="lengthInMins" type="number" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="format" class="col-sm-1 control-label">Format</label>
<div class="col-sm-offset-1 col-sm-5">
<select id="formatSelections" name="selections" class="form-control">
<option>Dvd</option>
<option>BluRay</option>
<option>Computer</option>
<option>Cloud</option>
</select>
</div>
</div>
<div class="form-group">
<label for="rating" class="col-sm-1 control-label">Rating</label>
<div class="col-sm-offset-1 col-sm-5">
<select id="ratingSelections" name="selections2" class="form-control">
<option>1</option>
<option>2</option>
<option selected>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-group">
<label for="favorites" class="col-sm-1 control-label">Favorite</label>
<div class="col-sm-offset-1 col-sm-5">
<select id="favoriteSelection" name="selections3" class="form-control">
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<input id="clear" name="clear" type="reset" value="Clear" class="btn btn-default" />enter code here
<input id="add" name="submit" type="submit" value="Add" class="btn btn-primary" />
</div>
</div>
</fieldset>
</form>
<div id="showMovies">
<fieldset>
<legend>List of Movies</legend>
<table class="table table-striped">
<thead>
<tr>
<th>Movie Id</th>
<th>Movie Title</th>
<th>Movie Year</th>
<th>Movie Length</th>
<th>Movie Format</th>
<th>Movie Rating</th>
<th>Favorite Movie</th>
</tr>
</thead>
<tbody id="movieData">
</tbody>
</table>
</fieldset>
</div>
</div>
<script src="../Scripts/homework3.js"></script>
</body>
</html>

You are forgetting to call function updateTableData() when loading page:
Make sure you are doing it by:
$(document).ready(function(){
updateTableData();
});
Also, your button shouldn't be submit type in order to not submit form, just throw Javascript events:
<input id="add" name="submit" type="button" value="Add" class="btn btn-primary" />
Finally, there's a method call to a non existant function:
hideshow("#formMovieData", 500, "#showMovies", 500);
You can just remove it from code. (I'm not seeing any advantage in using some hide/show effect on click "Add")
See an example in jsFiddle

Related

Can't save data from Html Asp.net Core to Mysql Using

I am learning frontend and I face this problem to save data from Html to Mysql in Asp.Net Core:
I have Order Model
OrderDetails Model
and I made ViewModel
Html table coded to add Rows dinamicly
And i get project , supplier and Item by viewdata as select items
All above it was done But can not save the record!!
<link rel="stylesheet" href="~/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="~/lib/font-awesome/css/all.min.css">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="~/css/style.css">
<!-- container -->
<div class="container" >
<div style="align-items:self-end">
<input type="button" onclick="enabled()" value=" New Purchace Order" style="margin:10px 10px;" id="newOrder" class="btn btn-info" />
</div>
#* <div class="row bg-info m-1 block">
<div class="text-center col-md-8">
<h1> Purchace Order <span id="countpro"></span></h1>
</div>
</div>*#
<!-- Order Section -->
#*<form asp-action="Create">*#
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row bg-secondary m-1 block">
<div class="col-md-4 col-sm-12">
<div class="form-group">
<label asp-for="OrderNO" class="control-label"></label>
<input asp-for="OrderNO" id="poNO" class="form-control" />
<span asp-validation-for="OrderNO" class="text-danger"></span>
</div></div>
<div class="col-md-4 col-sm-12">
<div class="form-group">
<label asp-for="OrderDate" class="control-label"></label>
<input asp-for="OrderDate" id="poDate" class="form-control" />
<span asp-validation-for="OrderDate" class="text-danger"></span>
</div></div>
<div class="col-md-4 col-sm-12">
<div class="form-group">
<label asp-for="Status" class="control-label"></label>
<input asp-for="Status" id="status" class="form-control" />
<span asp-validation-for="Status" class="text-danger"></span>
</div></div>
<div class="col-md-6 col-sm-12">
<div class="form-group">
<label asp-for="ProjectId" class="control-label"></label>
<select asp-for="ProjectId" id="project" class ="form-control" asp-items="ViewBag.ProjectId"></select>
</div></div>
<div class="col-md-6 col-sm-12">
<div class="form-group">
<label asp-for="SupplierId" class="control-label"></label>
<select asp-for="SupplierId" id="supplier" class ="form-control" asp-items="ViewBag.SupplierId"></select>
</div></div>
<div class="form-group">
<label asp-for="Subject" class="control-label"></label>
<input asp-for="Subject" id="subject" placeholder="Enter Order Description ...." class="form-control" />
<span asp-validation-for="Subject" class="text-danger"></span>
</div>
</div>
<!-- End Order Section -->
<!-- Item Section -->
<div class="row bg-primary m-1 block">
<div class="col-md-5 col-sm-12">
<div class="form-group">
<label asp-for="ItemId" class="control-label"></label>
<select asp-for="ItemId" id="item" asp-placeholder="Select Item ...." class ="form-control" asp-items="ViewBag.ItemId"></select>
</div></div>
<div class="col-md-1 col-sm-12">
<div class="form-group">
<label asp-for="UnitId" class="control-label"></label>
<select asp-for="UnitId" id="unit" class ="form-control" asp-items="ViewBag.UnitId"></select>
</div></div>
<div class="col-md-1 col-sm-12">
<div class="form-group">
<label asp-for="Qty" class="control-label"></label>
<input asp-for="Qty" id="qty" class="form-control" onkeyup="getTotal()" onchange="getTotal()"/>
<span asp-validation-for="Qty" class="text-danger"></span>
</div></div>
<div class="col-md-1 col-sm-12">
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" id="price" class="form-control" onkeyup="getTotal()" onchange="getTotal()" />
<span asp-validation-for="Price" class="text-danger"></span>
</div> </div>
<div class="col-md-2 col-sm-12">
<div class="form-group">
<label asp-for="Total" class="control-label"></label>
<input asp-for="Total" id="total" class="form-control bg-danger text-center" disabled value="0" />
<span asp-validation-for="Total" class="text-danger"></span>
</div></div>
<div class="col-md-2 col-sm-12">
<label class="control-label">Add</label>
<button class="btn btn-success " onclick=" addRow();" id="addButton">
<i class="fas fa-plus"></i></button>
</div>
</div>
<!-- End Item Section -->
<!-- Table -->
<table class="table " style="width:100%;" id="tablPro">
<thead>
<tr>
<th>#</th>
<th style="width:30%;">Product/Service</th>
<th style="width:10%;">Unit</th>
<th style="width:10%;">Qty</th>
<th style="width:10%;">Price</th>
<th style="width:15%;">Total</th>
<th style="width:5%;"></th>
<th style="width:5%;"></th>
</tr>
</thead>
<tbody id="tablePro">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<!-- End Table -->
<!-- Total Section -->
#* <div class="row bg-teal m-1 block" id="divPrint">*#
<div class="totalcontainer">
<div class="col-md-3 col-sm-12">
<label asp-for="SubTotal" style="color:Black;" class="control-label"></label>
<input asp-for="SubTotal" id="subTotal" class="form-control" />
<span asp-validation-for="SubTotal" class="text-danger"></span>
</div>
<div class="col-md-3 col-sm-12">
<label asp-for="Vat" style="color:Black;" class="control-label"></label>
<input asp-for="Vat" id="vat" class="form-control" />
<span asp-validation-for="Vat" class="text-danger"></span>
</div>
<div class="col-md-3 col-sm-12">
<label asp-for="GrandTotal" style="color:Black;" class="control-label"></label>
<input asp-for="GrandTotal" id="grandTotal" class="form-control" />
<span asp-validation-for="GrandTotal" class="text-danger"></span>
</div>
<div class="text-center">
<input type="submit" value=" + Save Purchace Order" id="saveBtn" style="margin:10px 10px;" class="btn btn-primary" />
</div>
</div>
<!-- End Total Section -->
<hr />
<!-- End Createor Section -->
<div class="row block">
<div class="col-md-3 col-sm-12">
<div class="form-group">
<label asp-for="CreatedBy" style="color:Black;" class="control-label"></label>
<input asp-for="CreatedBy" class="form-control" />
<span asp-validation-for="CreatedBy" class="text-danger"></span>
</div> </div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<label asp-for="TimeStamp" style="color:Black;" class="control-label"></label>
<input asp-for="TimeStamp" class="form-control" />
<span asp-validation-for="TimeStamp" class="text-danger"></span>
</div> </div>
</div>
<!-- End Createor Section -->
#* </form>*#
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/js/addRow.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/adminlte/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="~/lib/font-awesome/js/all.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
// $('#saveBtn').click(function() {
// var data = $('input').serialize();
// $.post(url, data, function(data) {
// console.log(data);
// });
//});
$(function () {
$("#saveBtn").click(function () {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "CreatePos/Create",
data: "{'poNo':'" + $("#poNO").val() +
"', 'poDate':'" + $("#poDate").val() +
"', 'status':'" + $("#status").val() +
"', 'project':'" + $("#project").val() +
"', 'supplier':'" + $("#supplier").val() +
"', 'Subject':'" + $("#Subject").val() +
"', 'item':'" + $("#item").val() +
"', 'unit':'" + $("#unit").val() +
"', 'qty':'" + $("#qty").val() +
"', 'total':'" + $("#total").val() +
"', 'subTotal':'" + $("#subTotal").val() +
"', 'vat':'" + $("#vat").val() +
"', 'grandTotal':'" + $("#grandTotal").val() + "'}",
async: false,
success: function (response) {
$("#poNO").val("");
$("#poDate").val("");
$("#status").val("");
$("#project").val("");
$("#supplier").val("");
$("#Subject").val("");
$("#item").val("");
$("#unit").val("");
$("#qty").val("");
$("#total").val("");
$("#subTotal").val("");
$("#vat").val("");
$("#grandTotal").val()
alert("record has been saved in database");
},
error: function () {
console.log("there is some error");
}
});
});
});
</script>
}
And her is the Script File
var value = document.getElementById('item');
var getItem = value.options[value.selectedIndex].text;
var unitValue = document.getElementById('unit');
var getUnit = unitValue.options[unitValue.selectedIndex].text;
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
var total = document.getElementById('total').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length);
var x = newRow.rowIndex - 1;
var editBtn =`<button class="btn btn-info" id="editRow">
<i class="fas fa-edit"></i>
</button>` ;
var deleteBtn =`<button class="btn btn-danger" onclick="deleteRow(this)">
<i class="fas fa-trash"></i>
</button>` ;
//defination of row cells
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
var cell5 = newRow.insertCell(4);
var cell6 = newRow.insertCell(5);
var cell7 = newRow.insertCell(6);
var cell8 = newRow.insertCell(7);
// Push row Values into tabel Body
cell1.innerHTML = x++;
cell2.innerHTML = getItem;
cell3.innerHTML = getUnit;
cell4.innerHTML = qty;
cell5.innerHTML = price;
cell6.innerHTML = total;
cell7.innerHTML = editBtn;
cell8.innerHTML = deleteBtn;
}
function getTotal() {
if (price.value != '') {
let result = price.value * qty.value;
total.value = result;
total.style.background = '#040';
let vatPercentage = 0.15;
let subtotal = document.getElementById('subTotal');
let vat = document.getElementById('vat');
let grandTotal = document.getElementById('grandTotal');
subtotal.value = total.value;
vat.value = subtotal.value * vatPercentage;
grandTotal.value = +vat.value + +subtotal.value;
}
else {
total.value = '';
total.style.background = '#a00d02';
}
}
Finally This is the controller
POST: CreatePos/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("OrderId,OrderNO,OrderDate,Subject,Status,CreatedBy,TimeStamp,ProjectId,SupplierId,ItemId,UnitId,Qty,Price,Total,SubTotal,Vat,GrandTotal")] CreatePoModel createPoModel)
{
if (ModelState.IsValid)
{
_context.Add(createPoModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["ProjectId"] = new SelectList(_context.Projects, "ProjectId", "ProjectName", createPoModel.ProjectId);
ViewData["SupplierId"] = new SelectList(_context.Suppliers, "SupplierId", "SupplierName", createPoModel.SupplierId);
ViewData["ItemId"] = new SelectList(_context.PoItems, "ItemId", "ItemName", createPoModel.ItemId);
ViewData["UnitId"] = new SelectList(_context.Units, "UnitId", "UnitCode", createPoModel.UnitId);
return View(createPoModel);
}
Please Consider that I am beginner still learning: (

Create dynamic input in dynamic form when I select an option

I am trying to create a dynamic form that adds another field when choosing Verification select, the problem is that when I add fields of options in Verification at the time of adding another form, the options that I previously added appear, as I do to add a new form and don't show added options? I appreciate your help thanks!
$(document).ready(function() {
$('.verificar-free').hide();
$('.duplicate-free').hide();
$('.optionRow').hide();
var count = 2;
//duplicate
$('a.add-free').on('click', function() {
//clone
var row = $('.duplicate-free').clone();
$(row).insertAfter('.aditional-box-free');
$(row).show();
//add new ids
$(row).find('select').attr('id', 'select-free_' + count);
//remove duplicate class
$(row).removeClass('duplicate-free');
//onchange of select
$('select').on('change', function() {
var value = $(this).val();
var select = $(this).parent();
if (value == 1) {
$(select).siblings('.input-free').show();
$(select).siblings('.ocultar-free').hide();
} else {
$(select).siblings('.input-free').hide();
}
if (value == 2) {
$(select).siblings('.ocultar-free').show();
$(select).siblings('.verificar-free').show();
} else {
$(select).siblings('.verificar-free').hide();
}
});
//add option
$(".addRow-free").click(function() {
var html = "<div class='option-free' id='" + count + "'><div class='form-group'><div class='input-group select'><input type='text' class='form-control' placeholder='Añade opción' /><span class='input-group-btn'><button class='btn btn-primary remove-option' type='button'><a class='remove-tipe' href='javascript: void(0)'><span class='glyphicon glyphicon-trash' style='color:white'></span></a></button></span></div></div></div>";
var form = $(html);
$(this).closest(".verificar-free").find(".optionRow-free").append(form);
});
count++;
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="aditional-questions text">
<div class="aditional-box-free">
<p class="aditional-text" for=""><b>Add Question</b>
<a class="btn btn-primary agregar add-free" href="javascript: void(0)" type="button"><span></span>Add</a>
</p>
</div>
<div class="duplicate-free all-free" style="text-align: center">
<div class="box-question">
<div class="row">
<label class="type-question-text" for="">Question Type</label>
<div class="col-md-12">
<select class="form-control select">
<option value="1">Text</option>
<option value="2">Verification</option>
</select>
</div>
<div class="row ocultar-free">
<div class="col-md-12">
<label class="type-question-text" for="">Title</label>
<div class="form-group">
<input type="text" id="" class="form-control text general" placeholder="Question">
</div>
</div>
</div>
<!--aditional option-->
<div class="row verificar-free">
<div class="text">
<div class="col-md-6">
</div>
</div>
<div class="text option text" style="margin-top:10px;">
<a class="btn btn-primary addRow-free" href="javascript: void(0)" type="button"><span></span>Add Option</a>
</div>
<br>
<div class="form-group optionRow-free">
</div>
</div>
</div>
<br>
</div>
</div>
</div>
If I'm not wrong with your question.
The problem is you got same(duplicate) added input right? (If more than 1 question)
Change this line
$(".optionRow-free").append(form);
To
$(this).closest(".verificar-free").find(".optionRow-free").append(form);

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.

How to edit and update table row dynamically in jquery and HTML

I am adding rows to table dynamically,now i am trying to edit table rows.
I click on edit, values are getting in text boxes after edit values i am clicking the add button but i created like new row not updated.
Any mistakes in my code
<form class="form-horizontal" role="form" id="chargesForm">
<div class="col-md-6">
<div class="form-group ">
<label for="minAmt" class="col-lg-4 control-label">MinAmmount</label>
<div class="col-lg-6">
<input type="text" class="form-control" id="minAmt" name="minAmt" />
</div>
</div>
<div class="form-group ">
<label for="maxAmt" class="col-lg-4 control-label">MaxAmmount</label>
<div class="col-lg-6">
<input type="text" class="form-control" id="maxAmt" name="maxAmt"/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group ">
<label for="type" class="col-lg-4 control-label">Type</label>
<select size="1" id="type" name="type">
<option value="Flat" selected="selected">
Flat
</option>
<option value="Percentage">
Percentage
</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-actions btnzone">
<button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" ><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
<a class="btn btn-danger" ><i class=""></i>Back</a>
</div>
</div>
</form>
<form class="form-horizontal" role="form" id="chargestableForm">
<div class="col-md-12" style="height:150px;overflow:auto;margin-top:5px;">
<table id="charges" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;" >
<thead style="background-color:#CCE5FF">
<tr>
<th>MinAmmount</th>
<th>MaxAmmount</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
i added rows with the help of jquery
var i=0;
$("button#savebutton").click(function(){
var minAmt=$("#minAmt").val();
var maxAmt=$("#maxAmt").val();
var type=$("#type").val();
i++;
var new_row = "<tr id='row"+i+"' class='info'><td class='minAmt'>" + minAmt + "</td><td class='maxAmt'>" + maxAmt + "</td><td class='type'>" + type + "</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'></a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''></a></span></tr>";
$("table tbody").append(new_row);
$("#minAmt").val($('td.maxAmt').last().text()).prop("disabled","disabled");
$("#maxAmt").val('');
//$("#type").val('');
});
$(document).on('click', 'span.deleterow', function () {
$(this).parents('tr').remove();
return false;
});
$(document).on('click', 'span.editrow', function () {
$("#minAmt").val($(this).closest('tr').find('td.minAmt').text()).prop("disabled","disabled");
$("#maxAmt").val($(this).closest('tr').find('td.maxAmt').text()).prop("disabled","disabled");
$("#type").val($(this).closest('tr').find('td.type').text());
});
Hi you can follow this link, I have used your code and updated it a lil.
link: https://jsfiddle.net/u7ycrxph/
Updated Code :
currentRow = null;
$("button#savebutton").click(function(){
//....
if(currentRow){
$("table tbody").find($(currentRow)).replaceWith(new_row);
currentRow = null;
}
else{
$("table tbody").append(new_row);
}
....//
});
$(document).on('click', 'span.editrow', function () {
currentRow= $(this).parents('tr');
//....
});
Use replaceWith()
Add a hidden field to denote which row is being edited.
<input type="hidden" id="currentRow"/>
On Edit
$(document).on('click', 'span.editrow', function () {
$("#currentRow").val($(this).closest("tr").attr("id"));
}):
On the click of Save in Edit mode create a new row template with the updated values and replace the existing row with the new one.
$("button#savebutton").click(function(){
if($("#currentRow").val()){
var row = $("table tbody").find('#'+$("#currentRow").val());
// var updated_row = //Updated template of the existing row
row.replaceWith (updated_row);
$("#currentRow").val("");
}
});

Categories