I am using this dynamic form generation code . https://www.jqueryscript.net/form/dynamic-forms-fields.html#google_vignette
Example : https://www.jqueryscript.net/demo/dynamic-forms-fields/
I have modified the html to take option value as input . I am adding options from an array. I want all the options to be shown from that array , on "Add" new form again the same options should come.
<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>jQuery Dynamic Forms Plugin Example</title>
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.1.3/darkly/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/dynamic-form.js"></script>
<style>
.container { margin: 150px auto; }
h1 { margin-bottom: 50px; }
</style>
<script>
$(document).ready(function() {
var dynamic_form = $("#dynamic_form").dynamicForm("#dynamic_form","#plus5", "#minus5", {
limit:10,
formPrefix : "dynamic_form",
normalizeFullForm : false
});
$("#dynamic_form #minus5").on('click', function(){
var initDynamicId = $(this).closest('#dynamic_form').parent().find("[id^='dynamic_form']").length;
if (initDynamicId === 2) {
$(this).closest('#dynamic_form').next().find('#minus5').hide();
}
$(this).closest('#dynamic_form').remove();
});
});
function addLocation() {
var input_object1 = JSON.parse('[{"id":1,"name":"Pune","facilityType":"CAMPUS","feedback":true,"roomStateMode":2,"asDm":true,"defaultSlotId":3,"timezone":"Asia/Kolk ata","visitorKioskOtpAllow":true,"visitorKioskQrCode":true,"defaultSlotStartBefore":5,"visitorCheckInTemplate":"","visitorPassTemplate":"visitor-pass-horizontal","s howAttendance":true,"employeePassTemplate":"employee-pass-template_1.html","employeePassPreapprovedTemplate":"employee-pass-preapproved-template_1.html","employeePa ssAdminApprovalRequired":true,"employeePassMaxDays":15,"employeePassAllowExternalUsers":true,"employeePassAdminApprovalExternalUsers":true,"attendanceReportTemplate ":1,"visitorQuickCheckInTemplate":"visitor_quick_checkin_email_template.html","level":2,"deskGroupBookingAllow":true,"deskGroupBookingMaxPeople":5,"latitude":18.520 4,"longitude":73.8567,"city":"Pune","streetAddress":"","rosterMax":50,"rosterConfigType":1,"rosterAllowedUptoDays":30,"deskBookIfRoster":false,"disableDeskBookShift Option":true,"healthDeclarationNotificationPreHours":2,"healthDeclarationDeskBookingAutoCancelDays":3,"countryCode":"25","healthDeclarationDisableDeskCheckinWithout Pass":false,"deskBookingKioskQrCodeCheckin":true,"disableDeskBookAmenityOption":true,"deskBookMaxEndDays":10,"deskBookAvailableLevelWise":true,"deskBookingDisableCo worker":false,"deskBookingDefaultDuration":9,"deskBookingCovidVaccinationCertDisable":true,"visitorQuickInviteAllow":true,"visitorQuickInviteTitle":"test","visitorQ uickInvitePurpose":"Other","defaultRoomDisplayTheme":{"id":1,"name":"foo","homeImageId":215,"homeImageChecksum":"7c858c1e9e6c971cc360141e92fc918e","homeFontColor":" e5e0ec"}}]') ;
var input_object2 = JSON.parse('[1,8,11,83,37,88,40,42,41]');
var campush_from_dashboard = null;
// for the edit , it should look for the id
$.each(input_object1, function (index, value) {
if(campush_from_dashboard == null){
if (jQuery.inArray(value.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id
})).text(value.name)
.appendTo('[id^=location]');
}
}
$.each(input_object1[index].facilities, function (index1, value1) {
if (jQuery.inArray(value1.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id
})).text(value.name + value1.name)
.appendTo('[id^=location]');
}
$.each(input_object1[index].facilities[index].facilities, function (index2,
value2) {
if (jQuery.inArray(value2.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id,
"floorId": value2.id
})).text(value.name + value1.name + value2.name)
.appendTo('[id^=location]');
}
});
});
});
};
</script>
</head>
<body>
<div class="container">
<form method="POST">
<label class="form-label">Advanced Properties for Desk Usage Analysis (Optional)</label>
<div class="form-group" id="dynamic_form">
<div class="row">
<div class="col-md-12 ">
<label for="location" class="form-label">Location</label>
<select class="form-select" name="location" id="location" placeholder="Location"
aria-describedby="teamsFeedback" required class="selectpicker" multiple>
</select>
</div>
<div class="button-group mt-2 mb-2 col-12">
<a href="javascript:void(0)" class="btn btn-primary " id="plus5" >Add More Advance Properties</a>
Remove
</div>
</div>
</div>
</form>
</div>
</body>
this is the header which contains the search box and the ul in which the live search results should be showing up. It prints the information about the data items out to the console, which means that the data can be found but it doesn't change anything in the ul which is linked to be altered when search results are found. I also checked the jsonSerialize function and it seems to be correct.
<< ? php
//require_once('../Models/AuctionData.php');
require_once('../Models/AuctionDataSet.php');
$auctionDataSet = new AuctionDataSet();
$auctionDataSet = $auctionDataSet - > fetchSearch($_GET["q"]);
echo json_encode($auctionDataSet);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/my-style.css" rel="stylesheet">
<!--<script src="js/Script.js"></script>-->
<title>Auction Website -
<?php echo $view->pageTitle; ?>
</title>
</head>
<body role="" document ">
<div class="container ">
<div class="row ">
<div id="title " class="col-xs-12 ">
<img src="images/iconhead.jpg "/>
<div class="pull-right "> <h1><?php echo $view->pageTitle ?> </h1></div>
</div>
</div>
<div class="row ">
<div id="menu " class="col-xs-6 col-sm-3 col-md-2 ">
<ul class="nav navbar_default nav-stacked ">
<li>Home </li>
<?php if(isset($_SESSION['id']))
{
echo " <li><a href='Logout.php'>Logout</a></li>"; } else{ echo "
<li><a href='Login.php'>Login</a></li>"; echo "
<li><a href='Register.php'>Register</a></li>"; } ?>
<form><input type="text" class="form-control input-lg" id="search" placeholder="search">
</form>
<ul class="list-group" id="txtHint"></ul>
</ul>
</div>
<script type=application/javascript>
document.addEventListener("DOMContentLoaded", readyPage);
function readyPage() {
let searchIn = document.getElementById("search");
searchIn.addEventListener("keyup", showHint);
console.log("ready");
}
function showHint(event) {
const text = event.target.value;
console.log(event);
let xmlhttp = new XMLHttpRequest();
let uic = document.getElementById("txtHint");
if (text.length > 1) {
xmlhttp.open("GET", "Ajax/ajaxSearch.php?q=" + text);
xmlhttp.send();
return;
}
if (text.length < 2) {
uic.innerHTML = "";
return;
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let data = JSON.parse(this.responseText);
let uic = document.getElementById("txtHint");
uic.innerHTML = "";
data.forEach(function(obj) {
console.log(obj);
uic.innerText += '<li class="list-group-item"><p>' + 'obj._id' + 'obj._title' + '</p>';
});
}
};
}
</script>
<div id="content" class="col-xs-6 col-sm-9 col-md-10">
I'm developing a COVID-19 tracker app so far it works but I'm having issue for when the user search for a country that isn't in the API a error message is suppose to pop up as the else statement, which indeed it does happen. The issue is the message would pop up when a country that's been entered and the API has the info the error message would still pop up. Any advice would help, thank you.
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if(getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
else {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
break;
}
}
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
The else part is replaced. If countriesIndex is not updated from 0 , that means the data is not found.
Fixed Code:
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if( getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
}
if(countriesIndex==0) {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
}
else{
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
I am using HTML and JavaScript for a Wi-Fi landing page (called Splash.html). With Splash.html I need to get variable names with document.getElementById and then set name with sessionStorage.setItem. This information is then retrieved by another html page (called Test.html) but when I am redirected to Test.html it replies with "0". I am not an expert but that says to me that the variable names are not being stored properly. Could someone please look at my code and offer some help?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="msapplication-TileColor" content="#0061da">
<meta name="theme-color" content="#1643a3">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<title>
SmartPlay TV
</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="jquery.mCustomScrollbar.css" rel="stylesheet">
<link href="wifi_landing.css" rel="stylesheet">
<script>
var rootPath = "/xxx/";
var defaultImgPath = "/xxx/assets/front/assets/images/products/7.png"
var firstPath = "http://xxx/xxx/";
</script>
</head>
<body>
<div id="login-form-bg-image-tablet">
<img id="back" src="back_5dc4a0740c93eclouds-1586540_960_720.jpg" onerror="this.src = '/xxx/assets/img/tablet.jpg'"></div>
<div class="page">
<div class="page-main">
<div class="row">
<div class="col-lg-3 col-md-12 col-sm-12 col-xs-12 landing-left">
<div class="row mark-img row-logo">
<div class="col-md-12 mark-img-rect">
<img id="logo" src="logo_5dc4a05f10a24201906271242crop479976885.jpg" onerror="this.src = '/xxx/assets/img/wifilanding-mark.png'"></div>
</div>
<div class="row mark-img row-url">
<div class="col-md-12 mark-mark-rect text-center">
<span id="url" style="word-break: break-word;">www.basicplasticsurgery.com</span>
</div>
</div>
<div class="row">
<div class="col-md-12 textarea-rect" style="display: flex;">
<span id="box_title" class="text3 text" style="padding: 20px 30px; background: white; width: 100%; position: unset; word-break: break-word; border: 2px solid grey;"><p>Welcome to Basic Plastic Surgery!<br><br>Your decision to improve your appearance can be one of the most important investments you make for yourselfâand your self-confidence. Our staff take every measure to ensure that you receive the highest quality care in a professional, comfortable environment.</p></span>
</div>
</div>
</div>
<div class="col-lg-9 col-md-12 col-sm-12 col-xs-12 landing-right">
<div class="row">
<div class="col-lg-9 col-md-12 col-sm-12 col-xs-12" id="gallery">
<div class="row media-rect">
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload1_5dbb7ff59f88074670796_10219304255335727_5029165459597950976_o.jpg" class="file-rect" id="upload1" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload1_desc">CoolSculpting.
Please see front desk for more info</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload2_5dc4a2905bfdb209508_4516468915805_534071624_o.jpg" class="file-rect" id="upload2" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload2_desc">Me playing soccer.</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload3_5dc4a2976ac89IMG_5313.JPG" class="file-rect" id="upload3" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload3_desc">BPS Background</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload4_5dcddf7d5131a20191017_220631.jpg" class="file-rect" id="upload4" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload4_desc">BPS
Test</span>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-12 col-sm-12 col-xs-12 landing-sign-rect">
<div class="landing-sign-rect-form">
<div class="menu1">
<span id="box_text" style="word-break: break-word;">In order to access the internet we need some information. Please submit the following info to use our wifi network.
If you don't submit information you cannot use our network.</span>
</div>
<div class="form-group">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_name" style="resize:none;" placeholder="First Name">Full Name</textarea></div>
<div class="form-group ">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_name1" style="resize:none;" placeholder="Last Name">Email</textarea></div>
<div class="form-group">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_email" style="resize:none;" placeholder="Email Address">Tell us what products you're interested in learning about:
</textarea></div>
<div class="form-group text-center">
<!-- <button class = "btn" type = "button" style = "background:#0073c3;color: white;">Sign In</button> -->
<!-- <form method="get" action="$authaction" onsubmit="SubmitFunc()"> -->
<form method="get" action="http://192.168.50.10:2050/nodogsplash_auth/" onsubmit="SubmitFunc()">
<input type="hidden" name="tok" value="$tok"><input type="hidden" name="redir" value="$redir"><input style="background:#0073c3;color: white;" type="submit" value="Sign In"></form>
</div>
<div class="menu3">
Powered by SmartPlay TV
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
It continues with JavaScript section:
<script>
function SubmitFunc() {
sessionStorage.clear();
var name = document.getElementById("user_name").value;
var name1 = document.getElementById("user_name1").value;
var email = document.getElementById("user_email").value;
sessionStorage.setItem("name", name);
sessionStorage.setItem("name1", name1);
sessionStorage.setItem("email", email);
}
function resize(obj) {
obj.style.height = "1px";
obj.style.height = (25 + obj.scrollHeight) + "px";
}
</script>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src="jquery.mCustomScrollbar.concat.min.js"></script>
<script src="custom_new.js"></script>
<script src="common.js"></script>
<script src="jquery.validate.js"></script>
<script>
initResize();
function alignTextBox() {
if (jQuery(window).width() < 770) {
jQuery(".media-rect").css("height", "");
jQuery(".textarea-rect .text2").css("min-height", "");
return;
} else {
jQuery(".textarea-rect .text2").css("min-height", "680px");
}
}
function initResize() {
var fileRectObj = jQuery(".file-rect").eq(0);
var width = fileRectObj.width();
var height = width * 9 / 16; // 16:9 to width
jQuery(".file-rect").css("height", height + "px");
alignTextBox();
}
jQuery(window).resize(function() {
initResize();
})
jQuery(document).ready(function() {
jQuery('.autosize').each(function() {
resize(this);
});
});
</script>
</body>
</html>
And here is the Test.html script that includes the getItem part:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Contact Form</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h3 style="margin-top: 100px; text-align: center;">Thank you for your submission. You can now browse the internet freely.</h3>
<script type="text/javascript">
function sendEmail1() {
console.log('sending email');
var name = localStorage.getItem("user_name");
var name1 = localStorage.getItem("user_name1");
var email = localStorage.getItem("user_email");
alert(name + name1 + email);
var xhr = new XMLHttpRequest();
// xhr.open('GET', 'sendEmail.php?name=john&name1=name1&email=test');
xhr.open('GET', 'http://192.168.50.10:8000/htdocs/sendEmail.php?name=' + name + '&name1=' + name1 + '&email=' + email);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {}
};
xhr.send();
}
function sendEmail2() {
console.log('sending email');
var name = localStorage.getItem("name");
var name1 = localStorage.getItem("name1");
var email = localStorage.getItem("email");
var xhr = new XMLHttpRequest();
// xhr.open('GET', 'sendEmail.php?name=john&name1=name1&email=test');
xhr.open('GET', 'sendEmail.php?name=' + name + '&name1=' + name1 + '&email=' + email);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
alert(xhr.responseText);
// return false;
}
};
xhr.send();
}
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
// alert('ready');
// alert(localStorage.getItem("email") + ":" + sessionStorage.getItem("email"));
// alert(sessionStorage.getItem("email") + ":" + localStorage.getItem("email"));
sendEmail1();
});
</script>
</body>
</html>
Test.html is using localStorage instead of sessionStorage.
I'm rather new to Javascript, so please excuse simple mistakes if I made any. I need to make a task board page. The user inputs a value (a task and a date) and JS saves it into an object. The object is pushed into an array and saved to Local Storage. After that, it fades in a note (did this with an image and CSS effects) and prints the value on top of it. To accomplish this I tried using a For loop to go through the array when I get it back from local storage, but it only keeps printing the first value the user entered.
This is my code:
var taskArray = [];
var imgs = document.getElementsByTagName("img");
$(document).ready(function hideImages() {
$("img").hide();
})
function saveToLocalStorage() {
//debugger;
var taskName = document.getElementById("task").value;
var taskDate = document.getElementById("date").value;
var task = {
name: taskName,
date: taskDate
}
taskArray.push(task);
var arrayToString = JSON.stringify(taskArray);
localStorage.setItem("user tasks", arrayToString);
var mainDiv = document.getElementById("maindiv");
var arrayFromStorage = localStorage.getItem('user tasks');
arrayFromStorage = JSON.parse(arrayFromStorage);
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML += `
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[x].name}
Complete by = ${arrayFromStorage[x].date}
</span>
`
x++
addText();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<title></title>
</head>
<body class="background-image">
<h1 class="pageheader">My Task Board</h1>
<form class="" action="index.html" method="post">
<div class="container">
<div class="row">
<input type="text" class="form-control col-sm centerInput" id="task" placeholder="Enter a Task">
<input type="date" class="form-control col-sm centerInput" id="date" value="">
</div>
<div class="form-group">
<input type="button" class="form-control btn btn-success" id="submit" value="Submit Task" onclick="saveToLocalStorage()">
</div>
<div class="form-group">
<input type="reset" class="form-control btn btn-success " id="reset" value="Reset Form">
</div>
</div>
</form>
<div class="imgContainer" id="maindiv">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<!-- load the script at the end of body tag -->
</body>
</html>
Any help would be greatly appreciated, cheers!
Try putting index instead of x in your loop.
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML +=
`
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[index].name}
Complete by = ${arrayFromStorage[index].date}
</span>
`
}