How can I display my data into another html after submit? I tried to store the value in local Storage and that didn't work out. How can i display the result in other page? In the below snippet i some how achieved to display data by using show and hide methods. But i'm looking to display my data in new HTML page.
var data = [
{
"username": "MADHU BABU POOJALA",
"skills": "BD",
"location": "Hyderabad",
"email": "rgw#yahoo.in",
"bscore": 856,
"ranking": 14652,
},
{
"username": "Mj",
"skills": ".net",
"location": "Hyderabad",
"email": "csaca#yahoo.in",
"bscore": 8540,
"ranking": 1452,
}
];
var result = [];
function Sort(val) {
result.sort(function (a, b) {
if (a[val] < b[val]) return -1;
if (a[val] > b[val]) return 1;
return 0;
});
searchResult(result);
}
function search(str) {
var str = str.trim().toUpperCase();
if (str !== '') {
var rslt = [];
for (var j = 0; j < result.length; j++) {
if (result[j].skills.toUpperCase().match(str)) {
rslt.push(result[j]);
}
}
searchResult(rslt);
} else {
searchResult(result);
}
}
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '',
location = $("#location").val() || '',
i;
result = []
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]
["email"].toUpperCase() === email.toUpperCase()) || (data[i]["location"].toUpperCase() ===
location.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
$(".ip").hide();
$(".tb").show();
var output = getResult();
searchResult(output);
});
$("#back").click(function () {
$('input[type="text"]').val('').removeAttr('checked').removeAttr('selected');
$('input[type="email"]').val('').removeAttr('checked').removeAttr('selected');
$(".tb").hide();
$(".ip").show();
});
function searchResult(output) {
var html = '';
$.each(output, function (key, value) {
html += '<div style="border:1px solid #000;padding:10px;margin:10px;">';
html += '<span style="font-weight:bold;">' + value.username + '</span>' +
'<br/>';
html += '<span>' + 'Email :' + '</span>' + '<span>' + value.email + '</span>' +
'<br/>';
html += '<span>' + 'Skills :' + '</span>' + '<span>' + value.skills + '</span>' +
'<br/>';
html += '<span>' + 'Location :' + '</span>' + '<span>' + value.location + '</span>' +
'<br/>';
html += '<span>' + 'B-score :' + '</span>' + '<span>' + value.bscore + '</span>' +
'<br/>';
html += '<span>' + 'Ranking :' + '</span>' + '<span>' + value.ranking + '</span>' +
'<br/>';
html += '</div>';
});
$('#table').html(html);
}
$(document).ready(function () {
$('#submit').attr('disabled', 'disabled');
$('input[type="text"]').keyup(function () {
if ($(this).val() != '') {
$('input[type="submit"]').removeAttr('disabled');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU"
crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
.results tr[visible='false'],
.no-result {
display: none;
}
.results tr[visible='true'] {
display: table-row;
}
.form-group {
position: fixed;
top: 30%;
left: 50%;
width: 1200px;
height: 200px;
background: #fff;
transform: translate(-15%, -50%);
}
</style>
</head>
<body>
<div class="ip">
<div class="form-group ">
<div class="col-4">
<label for="skills">Skills</label>
<input class="form-control" id="skills" type="text" placeholder="skills">
</div>
<div class="col-4">
<label for="email">Email</label>
<input class="form-control" id="email" type="text" placeholder="mail id">
</div>
<div class="col-4">
<label for="username">Username</label>
<input class="form-control" id="username" type="text" placeholder="username">
</div>
<div class="col-4">
<label for="location">location</label>
<input class="form-control" id="location" type="text" placeholder="location">
</div>
<br>
<div class="col-4">
<input id="submit" class="btn" type="submit" value="submit" disabled='disabled'>
</div>
</div>
</div>
<br>
<div style="display: none" class="tb">
<button class="btn" id="back">back to search</button>
<br>
<br>
<br>
<div class="container-fluid">
<div class="row">
<div class="left">
<label style="font-size: 20px;color: black;margin:0px">
Core Skills :
</label>
<input type="text" onkeyup="search(this.value)">
</div>
<div class="right">
<form>
<label style="font-size: 20px;color: black;margin:0px">
Sort By :
</label>
<select onchange="Sort(this.value)">
<option>-- select --</option>
<option value="username">A to Z</option>
<option value="bscore">B-score</option>
<option value="ranking">Ranking</option>
</select>
</form>
</div>
</div>
</div>
<div id="table">
</div>
</div>
</body>
</html>
Related
I need a little help here, so when i add an option from dynamic add select option and click order button it will display the options i picked.
For the next step, i need to count sum of the options i choose. I tried some tips i found earlier, but nothing works.
I have added a disabled input for the sum result. Any suggestion what method i can use here?
Here is the full code:
var data = {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function(option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function () {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function () {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function () {
$('.order').click(function () {
var selectMenu = {};
$("select.type").each(function (i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html("");
$.each(selectMenu, function (index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
})
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:50%">Item name</th>
<th style="width:50%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" disabled> <!-- sum price result here -->
</div>
As you are already using each loop to show your trs you can declare some variable i.e total and then inside each loop just use total += parseInt(data.total) and then show same inside your input .
Demo Code :
var data = {
Food: [{
id: 1,
name: "Fried Rice",
price: 1e4
}, {
id: 2,
name: "Fried Noodle",
price: 9e3
}, {
id: 3,
name: "Pancake",
price: 8500
}, {
id: 4,
name: "French Fries",
price: 7500
}],
Drink: [{
id: 1,
name: "Cola",
price: 4600
}, {
id: 2,
name: "Orange Juice",
price: 5400
}, {
id: 3,
name: "Mineral Water",
price: 3500
}, {
id: 4,
name: "Coffee",
price: 5800
}]
};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function(option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function() {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function() {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function() {
$('.order').click(function() {
var selectMenu = {};
$("select.type").each(function(i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html("");
var total = 0 //decalre this
$.each(selectMenu, function(index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
total += parseInt(data.total); //sum total
})
$(".totalPrice input").val(total) //show inside inputs
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:50%">Item name</th>
<th style="width:50%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" disabled>
<!-- sum price result here -->
</div>
I did not understand your question. But I think you want to sum all the price.
So I have made a little code for you. Hope it will work
let data= {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
let keys = Object.keys(data)
console.log(keys)//["Food", "Drink"]
let price = 0
for (let i = 0; i < keys.length; i++) {
let items = data[keys[i]] //Access the values of the key
for (let j = 0; j < items.length; j++) {
console.log(items[j].price) //10000 ....(in loop)
price = price + items[j].price
}
}
console.log(price)//54300
The expected behaviour of the code above is when I click the "Add" button the issue is created and is shown beneath the button. The problem is, nothing happens instead. I've been trying to search the web to find an answer but with no luck. Any idea what's wrong?
Here are my index.html and JavaScript:
document.getElementById('issueInputForm').addEventListener('submit', saveIssue);
function saveIssue(e) {
var issueDesc = document.getElementById('issueDescInput').value;
var issueSeverity = document.getElementById('issueSeverityInput').value;
var issueAssignedTo = document.getElementById('issueAssigntedToInput').value;
var issueID = chance.guid();
var issueStatus = 'Open';
var issue = {
id: issueID,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
if (localStorage.getItem('issues') === null) {
//var issues = [];
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
} else {
var issues = JSON.parse(localStorage.getItem('issues'));
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
}
document.getElementById('issueInputForm').reset();
fetchIssue();
e.preventDefault();
}
function setStatusClosed(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++)
if (issues[i].id === id)
issues[i].status = 'Closed';
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function deleteIssue(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++)
if (issues[i].id === id)
issues.splice(i, 1);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function fetchIssue() {
var issues = JSON.parse(localStorage.getItem('issues'));
var issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
var id = issues[i].id;
var desc = issues[i].description;
var severity = issues[i].severity;
var assignedTo = issues[i].assignedTo;
var status = issues[i].status;
issuesList.innerHTML += '<div class="well">' +
'<h6> Issue ID: ' + id + '</h6>' +
'<p><span class="label label-info">' + status + '</span></p>' +
'<h3>' + desc + '</h3>' +
'<p><span class="glyphicon glyphicon-time"></span>' + severity + '</p>' +
'<p><span class="glyphicon glyphicon-user"></span>' + assignedTo + '</p>' +
'Close' +
'Delete'+
'</div>';
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Issue Tracker</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body onload="fetchIssue()">
<div class="container">
<h1>JS IssueTracker</h1>
</div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueInputForm" >
<div class="form-group">
<label for="issueDescInput">Description</label>
<input type="text" class="form-control" id="issueDescInput" placeholder="Describe the issue...">
</div>
<div class="form-group">
<label for="issueSeverityInput">Severity</label>
<select id="issueSeverityInput" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedToInput">Assigned to</label>
<input type="text" class="form-control" id="issueAssignedToInput" placeholder="Enter responsible">
</div>
<button type="button" class="btn btn-primary">Add</button>
</form>
<div class="col-lg-12">
<div id="issuesList"></div>
</div>
<div class="footer">
<p>© Ida Djurhuus</p>
</div>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
As #epascarello already mentioned
type="button" does not submit forms
So change the type to submit
<button type="submit" class="btn btn-primary">Add</button>
From MDN
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
in your code 2 problem
1) change type="button" to type="submit"
2) var issueAssignedTo = document.getElementById('issueAssigntedToInput').value;
chaneg this line in id
var issueAssignedTo = document.getElementById('issueAssignedToInput').value;
document.getElementById('issueInputForm').addEventListener('submit', saveIssue);
function saveIssue(e) {
debugger;
var issueDesc = document.getElementById('issueDescInput').value;
var issueSeverity = document.getElementById('issueSeverityInput').value;
var issueAssignedTo = document.getElementById('issueAssignedToInput').value;
var issueID = chance.guid();
var issueStatus = 'Open';
var issue = {
id: issueID,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
if (localStorage.getItem('issues') === null) {
//var issues = [];
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
} else {
var issues = JSON.parse(localStorage.getItem('issues'));
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
}
document.getElementById('issueInputForm').reset();
fetchIssue();
e.preventDefault();
}
function setStatusClosed(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues[i].status = 'Closed';
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function deleteIssue(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues.splice(i, 1);
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function fetchIssue() {
var issues = JSON.parse(localStorage.getItem('issues'));
var issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
var id = issues[i].id;
var desc = issues[i].description;
var severity = issues[i].severity;
var assignedTo = issues[i].assignedTo;
var status = issues[i].status;
issuesList.innerHTML += '<div class="well">' +
'<h6> Issue ID: ' + id + '</h6>' +
'<p><span class="label label-info">' + status + '</span></p>' +
'<h3>' + desc + '</h3>' +
'<p><span class="glyphicon glyphicon-time"></span>' + severity + '</p>' +
'<p><span class="glyphicon glyphicon-user"></span>' + assignedTo + '</p>' +
'Close' +
'Delete'+
'</div>';
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<div class="container">
<h1>JS IssueTracker</h1>
</div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueInputForm" >
<div class="form-group">
<label for="issueDescInput">Description</label>
<input type="text" class="form-control" id="issueDescInput" placeholder="Describe the issue...">
</div>
<div class="form-group">
<label for="issueSeverityInput">Severity</label>
<select id="issueSeverityInput" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedToInput">Assigned to</label>
<input type="text" class="form-control" id="issueAssignedToInput" placeholder="Enter responsible">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
<div class="footer">
<p>© Ida Djurhuus</p>
</div>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
Have made few changes to your code:
Since element with type="button" cannot be associated with submit event, have changed the type as submit.
Added null check in fetchIssue function so that the code wont break when there are no issues.
Corrected a typo in the saveIssue function - document.getElementById('issueAssigntedToInput') to document.getElementById('issueAssignedToInput')
Declared variable "issues" in saveIssue function when the localStorage.getItem('issues') is null.
document.getElementById('issueInputForm').addEventListener('submit', saveIssue);
function saveIssue(e) {
var issueDesc = document.getElementById('issueDescInput').value;
var issueSeverity = document.getElementById('issueSeverityInput').value;
var issueAssignedTo = document.getElementById('issueAssignedToInput').value;
var issueID = chance.guid();
var issueStatus = 'Open';
var issue = {
id: issueID,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
var issues = [];
if (localStorage.getItem('issues') !== null) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
document.getElementById('issueInputForm').reset();
fetchIssue();
e.preventDefault();
}
function setStatusClosed(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues[i].status = 'Closed';
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function deleteIssue(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues.splice(i, 1);
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function fetchIssue() {
var issues = JSON.parse(localStorage.getItem('issues'));
if(typeof issues !== 'undefined' && issues !== null) {
var issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
var id = issues[i].id;
var desc = issues[i].description;
var severity = issues[i].severity;
var assignedTo = issues[i].assignedTo;
var status = issues[i].status;
issuesList.innerHTML += '<div class="well">' +
'<h6> Issue ID: ' + id + '</h6>' +
'<p><span class="label label-info">' + status + '</span></p>' +
'<h3>' + desc + '</h3>' +
'<p><span class="glyphicon glyphicon-time"></span>' + severity + '</p>' +
'<p><span class="glyphicon glyphicon-user"></span>' + assignedTo + '</p>' +
'Close' +
'Delete'+
'</div>';
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Issue Tracker</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body onload="fetchIssue()">
<div class="container">
<h1>JS IssueTracker</h1>
</div>
<h3>Add New Issue:</h3>
<form id="issueInputForm" >
<div class="form-group">
<label for="issueDescInput">Description</label>
<input type="text" class="form-control" id="issueDescInput" placeholder="Describe the issue...">
</div>
<div class="form-group">
<label for="issueSeverityInput">Severity</label>
<select id="issueSeverityInput" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedToInput">Assigned to</label>
<input type="text" class="form-control" id="issueAssignedToInput" placeholder="Enter responsible">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
<div class="footer">
<p>© Ida Djurhuus</p>
</div>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
I have populated the table on screen using a csv file. I need to filter this table using comma separated ID values(e.g 1,2,8,34) and show only those rows used in these values on the click of button 'Filter'.
HTML file -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello there</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript2.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
.guide {
text-decoration: underline;
text-align: center;
}
.odd {
color: #fff;
background: #666;
}
.even {
color: #666;
}
.hot {
border: 1px solid #f00;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>aaaaaaaaaaaaaaaaa</h2>
</div>
<div class="panel panel-primary">
<div class="panel-heading">pppppp</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6">
<input type="file" accept=".csv" id="fileUpload" /></div>
<div class="col-sm-6">
<input type="button" id="upload" class="btn btn-primary" value="Upload" /></div>
</div>
<div class="col-sm-7">
<div class="col-sm-2">
<input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" /></div>
<div class="col-sm-2">
<input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" /></div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12">
<center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="inputFilter" placeholder="Enter ID to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center>
</div>
<br />
<br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12"><p id="download" style="color:cornflowerblue; visibility:hidden"><strong>Please click the below links to download the processed file..</strong></p></div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3"><p id="File1" style="color:cornflowerblue;text-decoration:underline;visibility:hidden">File1 Download</p></div>
<div class="col-sm-3"><p id="File2" style="color:cornflowerblue;text-decoration:underline;visibility:hidden">File2 Download</p></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$("#cancel").on("click", function() {
$('input:checked').each( function() {
$( this ).closest("tr").remove();
});
});
$('#inputFilter').keyup(function () {
var that = this;
$.each($('tr'),
function (i, val) {
if ($(val).text().indexOf($(that).val()) == -1) {
$('#name').animate({
marginTop: 0
},
50,
function () {
$('tr').eq(i).hide();
});
} else {
$('#name').animate({
marginTop: 0
},
50,
function () {
$('tr').eq(i).show();
});
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
</script>
JavaScript2.js
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='name'/>");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
$("<td/>").html('<input type="checkbox" id='+cells[0]+'>').appendTo(row);
//alert(cells[0]);
for (var j = 0; j < cells.length; j++) {
$("<td/>").html('<input type="text" disabled value=' +cells[j]+ '>').appendTo(row);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
//document.getElementById("filter").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
Something like this -
EDIT#1
After using the script by #user3273700 , though the filter functionality works but every time the last column of my table shows 'Undefined'. The csv file looks like this -
And the table looks like this -
Modified HTML -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>J---</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript4.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
.guide {
text-decoration: underline;
text-align: center;
}
.odd {
color: #fff;
background: #666;
}
.even {
color: #666;
}
.hot {
border: 1px solid #f00;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>SAS</h2>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Aa</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6">
<input type="file" accept=".csv" id="fileUpload" />
</div>
<div class="col-sm-6">
<input type="button" id="upload" class="btn btn-primary" value="Upload" />
</div>
</div>
<div class="col-sm-7">
<div class="col-sm-2">
<input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
</div>
<div class="col-sm-2">
<input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12">
<center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="inputFilter" placeholder="Enter ID to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center>
</div>
<br />
<br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
</div>
<div class="col-sm-3">
<p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$("#cancel").on("click", function () {
$('input:checked').each(function () {
$(this).closest("tr").remove();
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
$("#filter").click(function () {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
</script>
Modified JavaScript4.js -
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
//var table = $("<table id='name'/>");
var lines = e.target.result.split("\n");
var result = [];
var headers = lines[0].split(",");
//alert(headers);
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
});
});
function populateTable(finalObject) {
var obj = finalObject;
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = Object.keys(obj[0]);
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html([columns[i]]);
row.append(headerCell);
}
$.each(obj, function (i, obj) {
row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
You can add a custom attribute (data-id) to each row while you append rows to your table and then use this reference to filter your table.
Try this working sample
$(function() {
var data = [{
id: "1",
name: "Ravi",
city: "Mumbai",
address: "Address1",
designation: "programer"
}, {
id: "2",
name: "Mohit",
city: "Delhi",
address: "Address1",
designation: "Project Manager"
}, {
id: "3",
name: "Mohan",
city: "Mumbai",
address: "Address1",
designation: "CEO"
}, {
id: "4",
name: "John",
city: "Landon",
address: "Address1",
designation: "programer"
}, {
id: "5",
name: "Jane",
city: "Landon",
address: "Address1",
designation: "programer"
}];
//set table header
var headRow = '<tr>';
$.each(data[0], function(attr, val) {
headRow += '<th>' + attr + '</th>'
});
headRow += '</tr>';
$("#my-table").append(headRow);
//add data rows to table
$.each(data, function(i, obj) {
row = '<tr data-id="' + obj.id + '"><td>' + obj.id + '</td><td>' + obj.name + '</td><td>' + obj.city + '</td><td>' + obj.address + '</td><td>' + obj.designation + '</td></tr>';
$("#my-table").append(row);
});
$("#filter-btn").click(function() {
ids = $("#filter-box").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function(i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="filter-box">
<button id="filter-btn">filter</button>
<table id="my-table">
</table>
I hope it will help
You are getting as undefined because it read last column of header row as "ADDRESS\r" (with a carriage return) instead of "ADDRESS". And when you use it to make your array of objects it set a property "ADDRESS\r" instead "ADDRESS".
So you need to remove it from your headers array like this.
var headers = lines[0].split(",").map(function(obj){
return obj.replace(/(?:\\[rn]|[\r\n]+)+/g,'');
});
Here is a working fiddle https://jsfiddle.net/1av8gzo5/
I am trying to pass the value of an input a user provides to a bootstrap table. User provides a name and a score. Currently it is being displayed right below the table instead of within it. How would I go about doing this. I've tried to append it using javascript but cant seem to figure it out. Thanks
You have to append data you have in rankings to the table as rows trs using the following line :
$('table').append('<tr><td>' + rankPosition + '</td><td> ' +rankings[i].name + '</td><td>'
+ rankings[i].score + ' pts</td></tr>');
Note : Add $('table tbody').empty() before the loop to reset table content.
Hope this helps.
$(document).ready(function() {
var scoreboard;
var rankings = [];
var displayScoreboard = function(rankings) {
var rankPosition = 1;
var tieScore = 0
var previousScore = 0;
$('#rankings').html('')
$('table tbody').empty();
for (var i = 0; i < rankings.length; i++) {
if (i > 0 && rankings[i-1].score !== rankings[i].score) {
rankPosition = rankPosition + tieScore +1;
}
$('table').append('<tr><td>' + rankPosition + '</td><td> ' +rankings[i].name + '</td><td> ' + rankings[i].score + ' pts</td></tr>')
}
}
var sortRankings = function(rankings) {
rankings.sort(function(a, b) {
return b.score-a.score;
});
};
$('#add').on('click', function() {
var playerName = $('#eq-name').val();
var playerScore = $('#eq-score').val();
if (playerName.length > 0 && playerScore.length > 0) {
var playerStats = {name: playerName, score: playerScore};
rankings.push(playerStats);
sortRankings(rankings);
displayScoreboard(rankings);
$('#eq-name').val('');
$('#eq-score').val('');
} else {
alert("Please enter a name and a score");
}
});
$('#clear').on('click', function() {
$('#rankings').html('');
rankings = [];
});
});
.eq-input {
display:block;
text-align:center;
vertical-align:middle;
width:100%;
height:100%;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>EverQuoteTest</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.scss">
</head>
<body>
<div class="container eq-input">
<input type="text" id="eq-name" placeholder="Name">
<input type="number" id="eq-score" placeholder="Score" min=0>
<br>
<br>
<button class="btn btn-success" id="add">Add To Rankings</button>
<button class="btn btn-danger" id="clear">Clear Rankings</button>
<a id="add-game" class="btn btn-default ">Add Game</a>
</div>
<div class="container">
<div class="col-md-8 col-md-offset-4">
<h3>Leaderboard</h3>
</div>
<table class="table" border="1">
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
</table>
<ul class="list-unstyled" id="rankings"></ul>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.0.0/lodash.min.js"></script> -->
<script src="js/main.js"></script>
</body>
</html>
Add this code:
$('.table')
.append('<tr><td>' + rankPosition + '</td><td>' + rankPosition + '</td><td>' +rankings[i].name + ', ' + rankings[i].score + ' pts</tr>');
Fiddle: http://codepen.io/anon/pen/dGdabG
I am currently creating a signup form for a client and one of the requirements is for the form to be able to transmit and store data offline. I have already tried to work with a database, but I am still in beginning stages learning php so I decided t quit while I am behind.
I found another method of storign data locally suing localstorage with JS, but I am unable to display the stored data in a dynamic table.
Any help on this matter would be greatky appreciated, here is the code I have so far
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem(), false);
window.onload = function() {
storageLogic.loaddata();
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>
There are primarily two errors you need to fix:
Move the getElementById() and addEventListener() for id btnsubmit to your onload handler. The way it is now, it tries to find the element before it is actually in the DOM.
You are accidentally invoking the handler that is the second parameter of addEventListener(). In other words, get rid of the () after the second parameter.
Here is a version of your code with those changes that seems to minimally work.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
window.onload = function() {
storageLogic.loaddata();
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem, false);
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>