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();
});
Related
I have a chrome extension generator and it downloads multiple files. I want it to put all the files in a new folder instead of downloading them all into the downloads folder, and then upload to chrome. If there is a way, that would be great, but that might not work because it installs an extension automatically? Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Extension Maker</title>
</head>
<body>
<form>
<h1>Extension maker for chrome</h1>
<input id="name" size="22" placeholder="Extension name">
<br>
<input id="vers" size="22" placeholder="Version">
<br>
<textarea id="desc" placeholder="Description"></textarea>
<br><br><br>
<input type="checkbox" id="popup">Popup <input id="popup-html" placeholder="Popup html">
<br>
<input type="checkbox" id="urlo">Change contents of single page <input id="page-cont" placeholder="Page HTML">
<select id="select">
<option value="newtab">New Tab Page</option>
<option value="bookmarks">Bookmarks Page</option>
<option value="history">History Page</option>
</select>
<br>
<input type="checkbox" id="js">Run JavaScript <input id="js" placeholder="JS">
<br><br><br>
<button onclick="downloadAll()" id="downloadbutton">Download</button>
</form>
<script>
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
};
function downloadAll() {
var first = document.getElementById("popup").checked;
var second = document.getElementById("urlo").checked;
var third = document.getElementById("js").checked;
var name = document.getElementById("name").value;
var vers = document.getElementById("vers").value;
var desc = document.getElementById("desc").value;
var pophtml = document.getElementById("popup-html").value;
var manifeststart = "{ 'name': " + name + ", 'version': " + vers + ", 'description': " + desc + ", 'manifest_version': 2 ";
if (first === true) {
var manifest = manifeststart + "'default_popup': 'popup.html', 'default_icon': { '16': 'images/get_started16.png' } },}";
var text = document.getElementById("popup-html").value;
var filename = "popup.html";
download(filename, text);
};
if (second === true) {
var select = document.getElementById("select").value;
var text = document.getElementById("select").value;
var manifest = manifest + "'chrome_url_overrides' : { ' " + select + "': 'myPage.html' }";
var text = document.getElementById("page-cont").value;
var filename = "myPage.html";
download(filename, text);
};
if (third === true) {
var manifest = manifest + "'background': {'scripts': ['background.js'],'persistent': false }";
var text = document.getElementById("js").value;
var filename = "background.js";
download(filename, text);
};
var manifest = manifest + ", }";
var text = manifest;
var filename = "manifest.json";
download(filename, text);
};
</script>
</body>
</html>
(also please tell me if there is anything wrong with the code)
Is this possible? Thanks in advance!
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>
I do a weather app for Free code camp, but i don't know why my button don't change the temperature from celsius to fahrenheit.
I think it's a problem for the recuperation of the variable but i don't know where.
I try some change in my code but i just go around in circles.
This is my javascript :
$(document).ready(function(){
var long;
var lat;
var celsius;
var fahrenheit;
navigator.geolocation.getCurrentPosition(function(position){
long = position.coords.longitude;
lat = position.coords.latitude;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&lang=fr'+'&units=metric&appid=d475e2ed504ab40f4de6c1b3cba9ebcc';
$.getJSON(url, function(data){
var weatherType = data.weather[0].description;
var windSpeed = data.wind.speed;
var icon = data.weather[0].icon;
var city = data.name;
var country = data.sys.country;
var description = data.weather[0].description;
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
$('.card').html( city + '<br> Temp: '+Temp+' °C'+ '<br> Wind Speed:'+windSpeed+'M/s');
$('.icon').html('<img src="http://openweathermap.org/img/w/' + icon + '.png" /> ' + '<br>'+weatherType);
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
$('.btn').on('click', function() { change (); })
console.log(city);
console.log(weatherType);
console.log(windSpeed);
console.log(icon);
};
})
})
});
and the HTML :
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<title>Weather App</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class='col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 weather' >
<div class="col-sm-6 text-center card">
</div>
<div class="col-sm-6 text-center text-uppercase icon">
</div>
<button type="button" class="btn degree">°C/°F</button>
</div>
</div>
</div>
<div class="text-center footer">by Mathieu Dupré-Fontana
</div>
<script src="js/app.js"></script>
Can somebody help me please?
Ps: Sorry for my bad English, i'm French .
celsius appears to be a number, not a string, when Temp is set to the value of celisus, Temp is set to a number, not a string
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
Temp would not be equal to "fahrenheit" or "celcius" within change function
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
}
.html() should also be called within change() function, if the expected result is to toggle Celcius and Fahrenheit rendering at HTML on click at element.
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
Hi I have a Pricing table that was created in javascript, what I need to know is how to pass the values in row 1 or 2 into a aspx page using javascript with the click of a button
Here my code:
<select style="padding:10px;background: #cb1c69;color: #FFFFFF; font-size:18px; border-radius: 11px;">
<option>Choose Your Plan</option>
<option value="red">Monthly</option>
<option value="green">Yearly</option>
<option value="blue">Perpetual</option>
</select>
Edition:
<div class="pricetable-column red box" style="width: 33.3333333333%; border-right:1px solid gray;">
<div class="pricetable-column-wall">
<div class="pricetable-header">
<div class="pricetable-fld-name">
Lite</div>
<div class="pricetable-header-inner">
<div class="pricetable-fld-price">
<span class="cur"></span>750/- Monthly</div>
<p>
( Minimum 6 Month)</p>
</div>
</div>
<div class="ribbon">
HOT</div>
<div class="pricetable-button-container1">
Buy Now
</div>
</div>
</div>
I want if i click the buy now button and value get go to another page. I mean billing options page
please help me sir
I don't know how to use javascript.
update code:
Source code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Name:
<input type="text" id="txtName" name="Name" value="Mudassar Khan" /><br />
<br />
Technology:
<select id="ddlTechnolgy" name="Technology">
<option value="ASP.Net">ASP.Net</option>
<option value="PHP">PHP</option>
<option value="JSP">JSP</option>
</select>
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "MyPage2.html?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>
Any problem my code:
Plese try this code according to your requirement:
Source Page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Name:
<input type="text" id="txtName" name="Name" value="Mudassar Khan" /><br />
<br />
Technology:
<select id="ddlTechnolgy" name="Technology">
<option value="ASP.Net">ASP.Net</option>
<option value="PHP">PHP</option>
<option value="JSP">JSP</option>
</select>
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<span id = "lblData"></span>
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>
You have multiple options to do so:
sessionStorage
Example:
sessionStorage.setItem('key', 'value');//to set value
sessionStorage.getItem('key');//to get the value
localStorage
Example:
localStorage.setItem('key', 'value');//to set value
localStorage.getItem('key');//to get the value
Cookies
Example: Ref
var createCookie = function(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
As a key in Query string
Ex:
http://www.example.com?myKey=myVal
If I understand correctly, you want to pass values that a user selects in one page to another page. I would recommend you to pass your values using key value pairs in the URL. JavaScript has neat way of doing it. For example :
var month = "July"
var date = "1"
var URL = "yourpage.aspx?month="+month+"&date="+date
location.href=URL
By this, the URL will look something like this youpage.aspx?month=July&date=1
The parameters in the URL start after the question mark "?" and the key value pairs are separated by "&". location.href will redirect your page to that URL. and then you can read these parameters using .net on the server side. I hope this helps.