I am working on web related applications.When i try to display sessionStorage item it returns "undefined".
IE settings also changed but still i am getting same.
Login.html page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var currentDate = new Date,
dformat = [(currentDate.getMonth() + 1),
currentDate.getDate(),
currentDate.getFullYear()].join('/') +
' ' +
[currentDate.getHours(),
currentDate.getMinutes(),
currentDate.getSeconds()].join(':');
function unicsession(length) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
var sess = "";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
sess += chars.charAt(i);
}
return sess;
}
function generate() {
var intime = dformat;
sessionStorage.setItem("logintime", intime);
var username = document.getElementById("Username").value;
sessionStorage.setItem("username", username);
var unisession = unicsession(5);
sessionStorage.setItem("unisession", unisession);
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input id="Username" type="text" />
</td>
</tr>
<tr>
<td>
Click here
</td>
</tr>
</table>
</body>
</html>
home.htm page code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var getid = sessionStorage.getItem("username");
var logintimes = sessionStorage.getItem("logintime");
var unicsessionid = sessionStorage.getItem("unisession");
var currentDate = new Date,
outformat = [(currentDate.getMonth() + 1),
currentDate.getDate(),
currentDate.getFullYear()].join('/') +
' ' +
[currentDate.getHours(),
currentDate.getMinutes(),
currentDate.getSeconds()].join(':');
function Getout() {
alert("Login Id: " + getid + " ; login Time: " + logintimes+" ; Unic Session-Id : "+unicsessionid+" ; Logout Time : "+outformat);
}
</script>
</head>
<body>
<input id="logout" type="button" value="Logout" onclick="Getout()"/>
</body>
</html>
When i click on login page it redirect to home page and after click on logout button in home page it displays undefined.
How can i resolve this issue.
Thanks in advance for help.
sessionStorage is not avialable from IE if you access your files via your local filesystem. Use any local server to serve your scripts as http
Related
Im working on this currency converting app and ufetching the API from https://exchangeratesapi.io/
The app works except it only fetches the api on refresh. Im using onload in body tag.
Any idea how can I make it work on first load without refreshing?
Thanks in advance
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>JS Bin</title>
<script type="text/javascript" src="indexCurrencyFirst.js" ></script>
<script type="text/javascript" src="indexCurrency.js" ></script>
<link rel="stylesheet" type="text/css" href="styleCurrency.css">
</head>
<body onload="convertCurrencyRight()" >
<nav>
<ul class="navbar">
<li id="logo"><img src="Assets/Logo_openCurren.svg"></li>
<li id="date">Fecha</li>
</ul>
</nav>
<div class="wrapper" >
<div id="containerFrom">
<input id="fromQuantity" type="number" value="1" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()"/>
<select id="from" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
</select>
</div>
<div id="arrow"><img src="Assets/Arrow.svg"> </div>
<div id="containerTo">
<input id="toQuantity" type="number" value="0" onchange="convertCurrencyLeft()" onkeyup="convertCurrencyLeft()"/>
<select id="to" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
<option value="EUR" selected>EUR</option>
</select>
</div>
</div>
<div class="wrapper" >
<div id="containerCValues">
<p id="currentRateA"> 1 Eur = 0.89 Gbp </p>
<p id="currentRateB"> 1 Gbp = 1.12 Eur </p>
</div>
</div>
</body>
</html>
My JS files
Loaded in head indexCurrencyFirst
//fill the select options with the available currencies
fetch("https://api.exchangeratesapi.io/latest?base=")
.then((resp) => resp.json())
.then(function(data){
var allRates = data.rates;
var selectA = document.getElementById("from");
var selectB = document.getElementById("to");
allRates = Object.entries(allRates)
for(var i = 0; i < allRates.length; i++) {
var opt = allRates[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
if(opt==="GBP"){
var selectedAtt=document.createAttribute("selected");
el.setAttributeNode(selectedAtt);
}
selectA.appendChild(el);
var la = document.createElement("option");
la.textContent = opt;
la.value = opt;
selectB.appendChild(la);
}
})
.catch(function(error) {
console.log(error);
});
and the functions which convert the rates
function convertCurrencyRight() {
var fromCurrency = document.getElementById("from").value;
var toCurrency = document.getElementById("to").value;
console.log(toCurrency);
fetch("https://api.exchangeratesapi.io/latest?base=" + fromCurrency)
.then((resp) => resp.json())
.then(function(data){
//if both currencies are the same return identical values
(fromCurrency===toCurrency) ?
(document.getElementById("toQuantity").value = document.getElementById("fromQuantity").value,
document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + "...",
document.getElementById("currentRateB").textContent= "")
:
//otherwise return the top value as the multiplication of top currency rate by the amount specied below
(document.getElementById("toQuantity").value = (data.rates[toCurrency]*document.getElementById("fromQuantity").value).toFixed(3),
//change the single amount values
document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + (data.rates[toCurrency]).toFixed(6) + " " + toCurrency,
document.getElementById("currentRateB").textContent= "1 " + toCurrency + " = " + (1/data.rates[toCurrency]).toFixed(6) + " " + fromCurrency)
//load the date of the current rates
var date = document.getElementById("date");
date.innerHTML = "LAST UPDATED " +
data.date.split("-").reverse().join("-");
})
.catch(function(error) {
console.log(error);
});
}
function convertCurrencyLeft() {
...
}
Any idea how to fix this. I tried using jQuery with document ready instead of onload with luck
I'd just get ride of the onload on your body tag and just go with Jquery $(document).ready() and put your call to `convertCurrencyRight() there. In my fiddle this appears to work fine.
$(document).ready(function() {
convertCurrencyRight();
});
In my project I need to see sensors data in textarea window
and after some time to save those data in txt file.
I use this code :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var updateInterval = 50;
var updateChart = function(count) {
count = count || 1;
Val1 = Math.floor((Math.random() * 100) + 1);
Val2 = Math.floor((Math.random() * 100) + 1);
Val3 = Math.floor((Math.random() * 100) + 1);
$(document).ready(function() {
var $textarea = $('textarea');
$textarea.scrollTop($textarea[0].scrollHeight);
});
var d = new Date();
$("#output").append(document.createTextNode(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " - , " + Val1 + ", " + Val2 + ", " + Val3 + "\n"));
}
setInterval(function() {
updateChart()
}, updateInterval);
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
Filename: <input type="text" name="name" value=" .txt">
<textarea id='output' cols="40" rows="10" name="text" style="border:solid 2px blue;">
Time ,Val1, Val2, Val3
</textarea>
<input type="submit" value="SAVE">
</form>
</body>
</html>`
The problem is in the fact: my code execution speed is slower and slower if time
between start and file saving moment is longer !
If I use 20 samples/sec this amount of slowdown is not acceptable.
Is it possible to get faster code and much less dependent of time (txt file size) ?
I am trying to get date & no. of instances spin-up on that day.
Here is my code , i am beginner in development & in javascript.
so forgive me in advance for any immature code.
after getting startdate & end date , dates are stored in listDate array.
hours of a day is stored in hourArray.
then using JS SDK for AWS to get no. of instances spinned up on specific date.
ec2.describeInstances is not working as expected here ,
sometimes , i got output from ec2.describeInstances correctly , but it is always picking end date in all while loop iterations.
most of the time , ec2.describeInstances doesnt even execute.
function applyFilters() {
var listDate = [];
demo1.innerHTML = '';
var startDate = document.getElementById("fromdate").value;
var endDate = document.getElementById("todate").value;
//alert(startDate);
//alert(endDate);
var dateMove = new Date(startDate);
var strDate = startDate;
while (strDate < endDate){
var strDate = dateMove.toISOString().slice(0,10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate()+1);
};
//alert(listDate);
//document.getElementById('demo1').innerHTML = "Your selected dates are";
//demo2.innerHTML += "<br>";
//document.getElementById('demo3').innerHTML = listDate;
alert(listDate);
var i = 0;
var j = listDate.length;
alert(j);
while (i < j){
alert(i);
alert(listDate[i]);
var hourArray = [];
var d = listDate[i];
for (var h = 0; h <= 9; h++) {
hourArray.push(d + 'T' + '0' + h + '*');
}
for (var m = 10; m <= 23; m++) {
hourArray.push(d + 'T' + m + '*');
}
alert(hourArray);
var ec2 = new AWS.EC2();
AWS.config.update({
region: "xxxxxxx",
accessKeyId: "xxxxxxxxxxxxxxxxxxxxx",
secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
i++;
var params = {
Filters: [
{
Name: 'launch-time',
Values: hourArray
}]
};
//alert("Specified launch-times are: " + hourArray);
ec2.describeInstances(params, function(err, data, d) {
//alert(data);
if (err) {
//demo5.innerHTML = 'ERROR:' + err;
console.log(err);
} else {
var no_of_inst = data.Reservations.length;
//demo4.innerHTML += "<br>";
//document.getElementById('demo5').innerHTML = 'Instances migrated on' + listdate[i] + 'are: ' + no_of_inst;
alert("Instances migrated on" + d + "are: " + no_of_inst);
}
});
}
}
<!DOCTYPE html>
<html>
<head>
<title>Migration Status</title>
<!--<link rel="stylesheet" href="styles.css">-->
<div>
<h3> M I G R A T I O N - S T A T U S </h3>
</div>
<meta charset="utf-8">
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.208.0.min.js"></script>
</head>
<body>
<p>Select Filters to get your ec2 graph :</p>
<form>
<div class = "css-grid1">
<label> Launch-time: </label>
</div>
<div class = "css-inlineblock1">
<label for="fromdate">From Date:</label>
<input type="date" id="fromdate" name="fromdate" min="2017-01-01">
<label for="todate">To Date:</label>
<input type="date" id="todate" name="todate">
</div>
<div class = "css-button">
<input type="submit" id="sbmt" onclick="applyFilters()">
</div>
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>
<div id="demo4"></div>
<div id="demo5"></div>
<div id="demo6"></div>
<div id="demo7"></div>
<div id="demo8"></div>
</form>
<script>
</script>
</body>
</html>
so i have just started to learn javascript, literally had 2 classes on it. So my knowledge is very very limited. But I am trying to make an appointment application and i keep receiving a Uncaught rangeError :Invalid string length error, and i have no idea why or how to fix it. Basically I have been given some code to copy without much explanation to it, so if anyone can help me with this error it would be greatly appreciated. The code where the error is appearing is below and i believe it is the line table += appt.tableRow(); which is causing the issue. There is obviously more to this code, but not sure if it needs to be given, as the issue is in the showTable function
Edit : I just added the whole javascript code to make it easier
var Appointment = function(subject, description,date, time) {
this.subject = subject;
this.description = description;
this.datetime = new Date(date + " " + time);
this.completed = false;
};
Appointment.prototype.isDue = function(){
var now = new Date();
if(this.datetime > now){
return false;
} else {
return true;
}
};
Appointment.prototype.whenDue = function(){
return this.datetime - new Date();
}
Appointment.prototype.toString = function(){
var s = this.subject +'\n'+
this.datetime.toString() + '\n';
if(this.completed){
s +="Not Completed\n\n";
}
return s
};
Appointment.prototype.howManyDaysTill = function() {
var ms = (this.datetime - new Date()) / 24/60/60/1000
return ms;
};
Appointment.prototype.howManyHoursTill = function () {
var hours = (this.datetime - new Date()) /60/60/1000
return hours;
};
Appointment.prototype.getDate = function() {
return this.datetime.toDateString();
};
Appointment.prototype.getTime = function (){
return (this.datetime.getHours()) + ":" + (this.datetime.getMinutes());
};
Appointment.prototype.tableRow = function(){
var tr = "<tr><td>" + this.getDate() + "</td><td>" +
this.getTime() + "</td><td>" + this.subject +
"</td></tr>";
return tr;
};
var appointments = [];
window.onload = function(){
var newButton = document.getElementById("new");
newButton.onclick = function () {
var subj = prompt("Enter a subject title for the appointment");
var desc = prompt("Enter a description for the appointment");
var date = prompt("Enter the appointment date in the format (e.g) 'Sep
25, 2012");
var time = prompt("Enter the appointment time in the format hh:mm");
var a = new Appointment((subj,desc,date,time));
appointments.push(a);
return showTable();
};
var showTable = function() {
var tableDiv = document.getElementById("table"),
table = "<table border='1'>" +
"<thead><th>Date</th><th>Time</th><th>Subject</th><th>Completed</th>
</thead>";
for (var i = 0, j = appointments.length; i < j; j++) {
var appt = appointments[i];
table += appt.tableRow();
}
table += "</table>";
tableDiv.innerHTML = table;
};
}
HTML5
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="appointments.js"></script>
<title>Appointments</title>
</head>
<body>
<button id="new">New Appointment</button>
<div id ="table"></div>
<header>
<h1>
Appointments Book
</h1>
<p> Enter appointment details and press OK to add, Cancel to revert.</p>
</header>
<table>
<tr>
<td>Subject : </td> <td>input type="text" size="40" id="subject"</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea rows = "5" cols=""50" maxlength="200" id="description">
</textarea>
</td>
</tr>
<tr> <td>Due Date:</td><td><input type ="date" id="duedate"/></td>
</tr>
</table>
<button id = "OK">OK </button><button id = "cancel">Cancel</button>
<hr/>
</body>
</html>
The for loop must increment on i and not on j. The current one is causing a infinite looping and hence the following line is creating a string that is too big to handle by the JS engine and hence the error
table += appt.tableRow();
I am trying to get id of x to change the value of a and print both values to .xls. I got part of it working properly (x will modify a) but it will not print to .xls properly. (says [object] instead of the value of variable x in the spreadsheet. Any help would be appreciated
<html>
<head>
<title>TEST</title>
<HTA:APPLICATION id="Test"
applicationName"Test"
caption="yes"
maximizeButton="no"
minimizeButton="no"
showInTaskbar="yes"
navigable="no"
singleInstance="yes"
scroll="no"
scrollFlat="yes" />
</HTA:APPLICATION>
</head>
<body>
<form id="TEST">
<h1>TEST</h1>
<input type="text" onblur="x1()" maxlength="2" id="X" />X <input type="text" maxlength="2" value="0" id="a" />a <br />
</form>
<script>
var fso = new ActiveXObject("Scripting.FileSystemObject");
var c = fso.CreateTextfile("z.xls",true);
c.WriteLine("X a");
c.close();
function x1() {
var X = document.getElementById("X");
var a = document.getElementById("a");
if (X.value == 1) {
a.value++;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var c = fso.OpenTextfile("z.xls",8,true);
c.Writeline("" + X + " " + a + "");
c.close();
} else {
if (X.value == 2) {
a.value--;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var c = fso.OpenTextfile("z.xls",8,true);
c.Writeline("" + X + " " + a + "");
c.close();
}
}
}
</script>
</body>
</html>
X and a points to an input tags. You need to get the value property.
(Just like you did in the line: if (X.value== 1) {)
Replace
c.Writeline(""+X+" "+a+"");
To
c.Writeline(""+X.value+" "+a.value+"");