Unable To See Calculated Field in LocalStorage using JavaScript - javascript

I have the following JS code for which I am calculating the insurance cost based on input provided by the user:
function AddQuote() {
if (ValidateInputs()) {
var json = {};
$(":input").each(function () {
json[$(this).attr("id")] = $(this).val();
});
var nextId = Number(localStorage.getItem('nextId'));
if (!nextId) {
nextId = 1;
}
localStorage.setItem("quote-" + nextId, JSON.stringify(json));
localStorage.setItem("nextId", String(nextId + 1));
$(location).prop('href', 'viewQuote.html?' + nextId);
}
}
function LoadQuoteData(id) {
var json = JSON.parse(localStorage.getItem("quote-" + id));
$(":input").each(function () {
$(this).val(json[$(this).attr("id")]);
});
var driverAge = Number(json['age']);
var driverExperience = Number(json['experience']);
var driverAccidents = Number(json['accidents']);
var subQuote;
var insuranceQuote = Number(json['finalQuote']);
if (driverExperience === 0) {
subQuote = 4000;
}
else if (driverExperience >= 1 && driverExperience <= 9) {
subQuote = 2500;
}
else {
subQuote = 1800;
}
if (driverAge >= 30 && driverExperience >= 2) {
insuranceQuote = subQuote * 0.75;
}
else {
insuranceQuote = subQuote;
}
//console.log(insuranceQuote);
console.log(json);
$("#finalQuote").val("$" + insuranceQuote);
}
I am using this in my HTML code as follows:
<script>
$(document).ready(function () {
var localStorageItems = Object.entries(localStorage);
var htmlCode = "";
$(localStorageItems).each(function () {
if ($(this)[0].startsWith("quote")) {
console.log($(this)[0]);
console.log($(this)[1]);
var quoteData = JSON.parse($(this)[1]);
var quoteAmount = "$" + quoteData['finalQuote'];
htmlCode +=
"<div class='container'>" +
"<div class='row pb-4 pt-4' style='border-bottom: 1px solid rgba(0,0,0,.125);'>" +
"<div class='col-md-6 '>" +
"<div class='card-header' style='margin-left: -1rem; margin-right: -1rem;'>Customer Information</div>" +
"<span class='d-block'><strong>First Name:</strong> " + quoteData['firstName'] + "</span>" +
"<span class='d-block'><strong>Last Name:</strong> " + quoteData['lastName'] + "</span>" +
"<span class='d-block'><strong>Address:</strong> " + quoteData['address'] + "</span>" +
"<span class='d-block'><strong>City:</strong> " + quoteData['city'] + "</span>" +
"<span class='d-block'><strong>Province:</strong> " + quoteData['province'] + "</span>" +
"<span class='d-block'><strong>Postal Code:</strong> " + quoteData['postalCode'] + "</span>" +
"<span class='d-block'><strong>Phone Number:</strong> " + quoteData['phone'] + "</span>" +
"<span class='d-block'><strong>Email:</strong> " + quoteData['email'] + "</span>" +
"</div>" +
"<div class='col-md-6'>" +
"<div class='card-header' style='margin-left: -1rem; margin-right: -1rem;'>Driving Information</div>" +
"<span class='d-block'><strong>Accidents:</strong> " + quoteData['accidents'] + "</span>" +
"<span class='d-block'><strong>Age:</strong> " + quoteData['age'] + "</span>" +
"<span class='d-block'><strong>Driving Experience:</strong> " + quoteData['experience'] + "</span>" +
"<span class='d-block'><strong>Insurance Quote:</strong> " + quoteAmount + "</span>" +
"<span class='d-block'><strong>" +
"</span>" +
"</div>" +
"</div>" +
"</div>" +
"</div>";
};
});
$("#quotesList").html(htmlCode);
});
</script>
But the problem is that the calculated finalQuote is not showing up on this HTML page (but all other fields are). Any ideas on what I'm missing / not doing correctly?

Related

How can I check checkbox which is exists in model sepereted by coma from database (as shown below in code) using MVC asp.net?

Below is code of javascript. I want my checkboxes are selected based on coma seperated values from database. please let me know where i am mistaken
function GetStatesList() {
debugger;
var makeList = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function(stateList) {
var makeChkList = ""
for (var i = 0; i < stateList.length; i++) {
var st = stateList[i];
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=\"" + #Model.States.Contains("Alaska") ? "checked" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function(r) {
OnFailure(r);
},
failure: function(r) {
OnFailure(r);
}
});
}
I found issue. because of js is client side and model loads before js load it was not getting modal value and to get value we have to use this line
#Html.Raw(Json.Encode(Model.States));
function GetStatesList() {
debugger;
var arrstates = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function (stateList) {
var makeChkList = ""
var st =#Html.Raw(Json.Encode(Model.States));
arrstates = st.split(",");
console.log(st);
for (var i = 0; i < stateList.length; i++) {
var str = stateList[i];
if (arrstates.includes(stateList[i])) {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=checked\"" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
else {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + i + "\" name=\"State_" + i + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function (r) {
OnFailure(r);
},
failure: function (r) {
OnFailure(r);
}
});
}

How to add delete button to a column using JS?

I have experience with PHP and HTML, but I am unfamiliar with JS. I have all the code needed, but I can't put it together. I have a table and need to add a delete button that will remove the file on that row. As shown in the picture below, but without the edit button:
When click on the Search button, the table is displayed (here is where I need the delete button):
index.php
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;'/>
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px; display:none">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
main.js
function Search(){
var crop = $("#crop").val();
var type = $("#type").val();
var year = $("#year").val();
var season = $("#season").val();
var location = $("#location").val();
var subLocation = $("#sublocation").val();
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
$.ajax({
url: "Resources/PHP/Search.php",
dataType: 'text',
data: {
crop: crop,
type: type,
year: year,
location: location,
season: season,
sublocation: subLocation
},
success: function(response) {
var data = JSON.parse(response);
var items = "";
var firstSet = 0;
if (data.length > 0)
{
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
$("#imported-set-wrapper").html(table);
$.each(data,function(index,item)
{
if (index == 0){
firstSet = item.ID;
}
items+= "<tr id='data-set-" + item.ID + "' onclick='SelectDataSet(\"" + item.ID + "\"); return false;' style='cursor:pointer'>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
var rowHeight = 61;
var padding = 10;
var actualHeight = (data.length + 1) * rowHeight + padding;
var maxHeight = 300;
var height = actualHeight < maxHeight ? actualHeight : maxHeight;
$('#imported-set-table').fxdHdrCol({
fixedCols: 0,
width: 1100,
height: height,
colModal: [
//added
{ width: 150, align: 'center' },
//added
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 250, align: 'center' },
{ width: 175, align: 'center' },
{ width: 150, align: 'center' },
],
sort: false
});
if (firstSet > 0){
$("#next").prop("disabled", false);
SelectDataSet(firstSet);
$("#data-set-fs").show();
} else {
alert("No dataset found");
}
}
$("#processing").hide();
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
$("#processing").hide();
}
});
}
Useful code from picture 1
"<input id='delete-" + type + "-" + item.ID +"' type='image' class='image-button delete-button' src='Resources/Images/delete.png' alt='Delete' onclick='Delete(" + item.ID +", \"" + type + "\"); return false;' title='Delete'>" +
"<input id='confirmDelete-" + type + "-" + item.ID +"' type='image' class='image-button confirm-delete-button' src='Resources/Images/confirm.png' alt='Confirm' style='display:none' onclick='ConfirmDelete(" + item.ID +", \"" + type + "\"); return false;' title='Confirm'>" +
"<input id='cancelDelete-" + type + "-" + item.ID +"' type='image' class='image-button cancel-delete-button' src='Resources/Images/cancel.png' alt='Cancel' style='display:none' onclick='CancelDelete(" + item.ID +", \"" + type + "\"); return false;' title='Cancel'>" +
function Delete(id, type){
$('#confirmDelete-' + type + '-' + id).show();
$('#cancelDelete-' + type + '-' + id).show();
$('#delete-' + type + '-' + id).hide();
CancelEdit(id);
}
function CancelDelete(id, type){
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
}
function ConfirmDelete(id, type){
$.ajax({
url: 'Resources/PHP/' + type + '.php',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
alert("The " + type + " has been deleted.");
GetList(type);
} else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});
}
Additional info: "//added" are additional lines trying to achieve mentioned goal.
You can add your button like this "<button data-id = " + item.ID + " class='delete'>Delete</button>" where data-id has your item.ID value this will get passed to your backend to perform delete operation.
Then , when delete button get clicked this $(document).on("click", ".delete",.. will get called you can show confirm-box so if user click ok then call your ajax to delete that trs data using selector.closest('tr').remove() where selector refer to the button which has been clicked .
Demo Code :
//dummy datas
var data = [{
"Year": "2016",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "1"
}, {
"Year": "2017",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "2"
}]
function Search() {
//some codes..
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
//other codes...
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
var items = "";
$("#imported-set-wrapper").html(table);
$.each(data, function(index, item) {
if (index == 0) {
firstSet = item.ID;
}
items += "<tr id='data-set-" + item.ID + "' onclick='' style='cursor:pointer'>" +
"<td style='overflow:hidden'>" +
//added button with data-* attribute
"<button data-id = " + item.ID + " class='delete'>Delete</button>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
//soem ot//other codes..
}
//onclick of delete button
$(document).on("click", ".delete", function() {
var id = $(this).data('id'); //get id
var selector = $(this);
console.log(id)
//show confirm box if yes
if (confirm("Are you sure?")) {
//ajax call
/*$.ajax({
url: 'url',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {*/
selector.closest('tr').remove() //remove tr
/* } else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});*/
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;' />
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px;">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
Where you have:
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
Doesn't this need to be the button? E.g.
<td><button onclick='deleteFunction(item.id)'>Delete</button></td>

How order table after selected option

I have URL API and i did group by "date".
But I would like to know how I can after I selected option from the data Importance its will order only the rows (and keep the date) by Importance.
Image how its order now:
http://prntscr.com/ebgodq
My code:
var table = $(".top-table");
var body = table.children("tbody");
var regdate = /^(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})$/;
$.get("http://api.tradingeconomics.com/calendar?c=guest:guest", function (data) {
showData(data);
});
function showData (data) {
//---Sort the data from the server
data.sort(function (a, b) {
return (new Date(a.Date)) - (new Date(b.Date));
});
var group = data.reduce(function (before, current) {
var day = current.Date.replace(regdate, "$1");
var hour = current.Date.replace(regdate, "$2");
if (!before[day]) {
before[day] = [];
}
current.Hour = hour;
before[day].push(current);
return before;
}, {});
for(var date in group) {
body.append("<tr style='text-align: left;background: #fafafa;line-height: 35px;border-bottom: 2px solid #ff9d00;font-size: 13pt;font-weight: normal;'>" +
"<th width='50%'>" + date + "</th>" +
"<th width='12%'>Actual</th>" +
"<th width='12%'>Previous</th>" +
"<th width='12%'>Forecast</th>" +
"<th width='4%'></th></tr>");
group[date].forEach(function(row){
var rowA = parseInt(row.Actual) > 0 ?
"<span style='color:red;'>" + noCommas(row.Actual) + "</span>" :
"<span style='color:green;'>" + noCommas(row.Actual) + "</span>";
var rowB = parseInt(row.Previous) > 0 ?
"<span style='color:red;'>" + noCommas(row.Previous) + "</span>" :
"<span style='color:green;'>" + noCommas(row.Previous) + "</span>";
var rowC = parseInt(row.Forecast) > 0 ?
"<span style='color:red;'>" + noCommas(row.Forecast) + "</span>" :
"<span style='color:green;'>" + noCommas(row.Forecast) + "</span>";
var Time = hourwithAMPM(row.Date);
body.append("<tr style='border-bottom: 1px solid #eeeeee;text-align: left;font-size: 12pt;font-weight: 300;line-height: 30px;'>" +
"<td><span class='im-" + row.Importance + "'>" + Time + "</span>" +
"<span style='margin: 0 10px 0;'><img src='/images/calendar/flags/" + noCommas(row.Country) + ".png' width='16' height='16' /></span>" +
"<span style='font-size: 11pt;color:#999999;font-weight: 600;word-spacing: -1px;margin: 0 5px 0;'>" + noCommas(row.Event) + "</span>"+
"<span style='color:#333333;'> " + noCommas(row.Reference) + "</span>" +
"</td>" +
"<td>" + rowA + "</td>" +
"<td>" + rowB + "</td>" +
"<td>" + rowC + "</td>" +
"<td><div class='arrow-down'></div></td>" +
"</tr>");
body.append("<tr class='showRow' style='display:none;'><td>yay!!!</td></tr>");
});
}
}

lightbox video popup for youtube channel video

When I click on the image video popups but does not play i.e. shows only loading symbol.
My js code is
function showVideoList(channelid, rows, maxnumbervideos, apikey) {
try {
var videoinfo = JSON.parse(getJSONData("https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelid + "&maxResults=" + maxnumbervideos + "&key=" + apikey));
var videos = videoinfo.items;
var videocount = videoinfo.pageInfo.totalResults;
// video listing
for (var j = 0; j < 3; j++) {
debugger;
//document.body.innerHTML+= "<div class='row'>" ;
// var div = document.getElementById("row");
//var append = "<div class='row'>"
$("#row").append("<div class='row'></div>");
for (var i = 0; i < 3; i++) {
var videoid = videos[i].id.videoId;
var videotitle = videos[i].snippet.title;
var videodescription = videos[i].snippet.description;
var videodate = videos[i].snippet.publishedAt; // date time published
var videothumbnail = videos[i].snippet.thumbnails.default.url; // default, medium or high
$('div.row').last().append("<div class='col s12 m4 l4'>"
+ "<div class='blog-post'>" + " <div class='card'> " + " <div class='card-image'> "
+ "<a href=https://www.youtube.com/watch?v=" + videoid + " target='_blank' class='voverlay'>"
+ "<img src='" + videothumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + videotitle + "' title='"
+ videotitle + "' /></a>"
+"</div>"
+ " <div class='card-content blog-post-content'> "
+ "<h2><a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>" + videotitle + "</a></h2>"
+ " <div class='meta-media'> "
+ "<div class='single-meta'>" + " Post By <a href='#'>Admin</a>" + " </div> "
+ " <div class='single-meta'> " + " Category : <a href='#'>Web/Design</a> " + " </div> "
+ " </div> "
+ " <div class='card-action'> "
+ " <a class='post-comment' href='#'><i class='material-icons'>comment</i><span>15</span></a> "
+ " <a class='readmore-btn' href='blog-single.html'>Read More</a> "
+ " </div> "
+"</div>" + "</div>" + "</div>" + "</div>"
);
}
document.body.innerHTML+="</div>";
// append += "</div>";
// div.innerHTML = append;
}
} catch (ex) {
alert(ex.message);
}
}

Conference website event schedule behaviour

I am building a conference website with some concurrent sessions in the schedule.
As you can see in the screenshot the seminar 3 is supposed to be concurrent with seminar 1 & 2 but they are separated. Below kindly find the relevant code. Could anyone tell what the reason might be?
Screenshot of Event Schedule in my Website
_addNewContent = function (msg) {
var lastBlock = false;
var lastConcurrent = false;
if (_page == 1) {
_wrapper.html('');
}
$.each(msg.sessions, function (i) {
if (lastBlock) {
var lastTime = lastBlock.find('.schedule__time').text();
lastTime = lastTime.split('-');
if ($.trim(lastTime[0]) == this.time) {
if (!lastConcurrent) {
lastConcurrent = $('<div class="schedule__concurrent"></div>').appendTo(_wrapper);
}
lastConcurrent.append(lastBlock);
} else {
if (lastConcurrent) {
lastConcurrent.append(lastBlock);
lastConcurrent = false;
} else {
_wrapper.append(lastBlock);
}
}
}
var newBlockString = '<div class="schedule__item ' + _dropdown + ' more-content__item">' +
'<time class="schedule__time" datetime="' + this.time + '">' + this.time + ' - ' + this.end_time + '</time>' +
'<h2 class="schedule__event">' + this.post_title + '</h2>' +
'<div class="schedule__details">';
if (_dropdown) {
newBlockString += ' <a class="schedule__close" href="#"><i class="fa fa-times"></i></a>';
}
newBlockString += '<i class="fa fa-location-arrow"></i> ' + this.location + '' +
'<div class="schedule__layout">' +
'<div class="schedule__speakers-group">'; // schedule__speakers-group
$.each(this.speakers, function () {
var speaker_image = '';
if (typeof (this.post_image[0]) !== 'undefined') {
speaker_image = 'background-image: url(' + this.post_image[0] + ')';
}
var favourite = this.featured ? 'speakers-favorite speakers-favorite_small' : '';
newBlockString += '<a href="' + this.url + '" class="schedule__speaker">' + // schedule__speaker
'<div class="schedule__speaker-pic ' + favourite + '" style="' + speaker_image + '">' +
'<span class="schedule__speaker-hover">' + msg.strings.view_profile + '</span>' +
'</div>' +
'<h3 class="schedule__speaker-name">' + this.post_title + '</h3>' +
'</a>'; // /schedule__speaker
});
newBlockString += '</div>' + // /schedule__speakers-group
'<div class="schedule__info">' +
'<div class="schedule__text">' + this.post_excerpt + '</div>' +
'<div class="schedule__labels">';
$.each(this.tracks, function () {
newBlockString += '<span class="label" style="background-color:' + this.color + ';">' +
this.name +
'</span> ';
});
newBlockString += '</div>' +
'' + msg.strings.more_info + '' +
'</div>' + // /schedule__info
'</div>' + // /schedule__layout
'</div>' + // /schedule__details
'</div>'; // /schedule__item
var newBlock = $(newBlockString);
if (msg.sessions.length == 1 || msg.sessions.length == i + 1) {
_wrapper.append(newBlock);
}
lastBlock = newBlock;
});
var newItems = _wrapper.find('.hidden');
setTimeout(function () {
$.each($('.schedule__items'), function () {
new ScheduleOpen($(this));
});
}, 10);
setTimeout(function () {
_heightAnimation(msg.has_items, newItems);
}, 50);
},
I guess your website first read an array of conference sessions before running this whole function.
And I found this part
if (msg.sessions.length == 1 || msg.sessions.length == i + 1) {
_wrapper.append(newBlock);
}
may prevents some of the conference sessions becoming concurrent to the last conference session, especially the last array item.
You can change it to
if (msg.sessions.length == 1) {
_wrapper.append(newBlock);
}
if (msg.sessions.length == i + 1) {
if (lastConcurrent) {
lastConcurrent.append(newBlock);
} else {
_wrapper.append(newBlock);
}
}

Categories