I have problem withe code geoloaction auto. When pressing the button, the current location has an error:
Uncaught TypeError: Cannot read property 'coords' of undefined
code:
var date = new Date();
var Today = date.getDay();
function loadWeather(cityCoords){
var latlng = cityCoords.coords.latitude + "," + cityCoords.coords.longitude;
var forecastURL = "https://api.forecast.io/forecast/3a6d5408bc15a469385cf59ee96c0205/" + latlng +"?lang=ar&si&raw";
$.ajax({
url: forecastURL,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
updateCurrentWeather(json);
weeklyForecast(json);
},
error: function(e) {
console.log(e.message);
}
});
}
function updateCurrentWeather (json) {
$("#current_temp").html(Math.round(json.currently.temperature) + "; C");
$("#current_summary").html ( " الحالة الجوية : "+ json.currently.summary) ;
$("#current_temp").attr("data-icon",icons[json.currently.icon]);
$("#current_windSpeed").html( " الرياح : "+json.currently.windSpeed);
}
function weeklyForecast (json) {
var Day = Today;
var outhtml;
for ( var i = 0; i <= 6; i++)
{
outhtml = "";
Day = Day + 1
//check if day is greater than number in week
if ( Day === 7) {
Day = 0;
}
//format html
outhtml = '<li><h3 class="icon" data-icon="' + icons[json.daily.data[i].icon] + ' ">' + days[Day];
outhtml = outhtml + (json.daily.data[i].summary);
outhtml = outhtml + ", العليا " + Math.round(json.daily.data[i].temperatureMax) + "° C ";
outhtml = outhtml + " , صغرى " + Math.round(json.daily.data[i].temperatureMin) + "° C ";
outhtml = outhtml + '</h3></li>';
//append new html li item to list view
$(".WeekForecast").append(outhtml);
}
}
function loadDefaultCity() {
loadCity("Baghdad");
}
function loadCity(city) {
$("#location").html(city);
if (city.toLowerCase() == "current location") {
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(loadWeather, loadDefaultCity);
} else {
loadDefaultCity();
}
} else {
loadWeather(cities[city.toLowerCase()]);
}
}
another data javascript appears cities[city.toLowerCase()] is defined
var icons = {
"clear-day" : "B",
"clear-night" : "C",
"rain" : "R",
"snow" : "G",
"sleet" : "X",
"wind" : "S",
"fog" : "N",
"cloudy" : "Y",
"partly-cloudy-day" : "H",
"partly-cloudy-night" : "I",
};
var cities = {
"baghdad" : { coords : { latitude : "33.3333", longitude: "44.3833" }},
"current location" : ""
};
var days = {
"0" : "الاحد : ",
"1" : "االاثنين : ",
"2" : ": الثلاثاء",
"3" : "الاربعاء : ",
"4" : "الخميس : ",
"5" : "الجمعة : ",
"6" : "السبت : "
};
var hours = {
"0" : "1",
"1" : "2",
"2" : "3",
"3" : "4",
"4" : "5",
"5" : "6",
"6" : "7",
};
Related
I have a form that gets weather information on locations based on user input. I am attempting to set custom validation messages for my input fields but they will not display.
I was under the impression that the submitting the form would still prompt them to display if I did not include preventdefault in the js but it seems that maybe this isn't the case.
Is there an alternative method of having the error messages display in this manner? I am trying to avoid using alerts if possible.
I'm still working out the concepts, so apologies for the sloppy formatting.
$(document).ready(function () {
var inputType = 1;
$("#Radio1").click(function() {
$("#lbl1").text("City Name:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
$("#Firstbox").attr({
"type" : "text",
"pattern" : "[a-zA-Z]{2,}",
"value" : "Regina",
"setCustomValidity" : "Must be 2 or more characters in length"
});
$("#Secondbox").attr({
"type" : "text",
"pattern" : "[a-zA-Z]{2}",
"value" : "ca",
"setCustomValidity" : "Must be 2 characters in length"
});
inputType = 1;
});
$("#Radio2").click(function() {
$("#lbl1").text("Postal Code:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
$("#Firstbox").attr({
"type" : "text",
"pattern" : "[A-Z][0-9][A-Z]",
"value" : "S4X",
"setCustomValidity" : "Must follow format: S4X"
});
$("#Secondbox").attr({
"type" : "text",
"pattern" : "[a-zA-Z]{2}",
"value" : "ca",
"setCustomValidity" : "Must be 2 characters in length"
});
inputType = 2;
});
$("#Radio3").click(function() {
$("#lbl1").text("Latitude:");
$("#lbl2").text("Longitude:");
$("#Firstbox").removeAttr("pattern");
$("#Secondbox").removeAttr("pattern");
$("#Firstbox").attr({
"type" : "number",
"min" : "-90",
"max" : "90",
"step" : "any",
"value" : "50.4",
"setCustomValidity" : "Must be betwen -90 and 90"
});
$("#Secondbox").attr({
"type" : "number",
"min" : "-180",
"max" : "180",
"step" : "any",
"value" : "-105.5",
"setCustomValidity" : "Must be betwen -180 and 180"
});
inputType = 3;
});
$("#SearchButton").click(function () {
if (checkValidity()) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var SearchResponse = this.responseText;
document.getElementById("ResponseText").innerHTML = SearchResponse;
var obj = JSON.parse(SearchResponse);
var city_name = obj["name"];
var country_name = obj["sys"]["country"];
var weather_description = obj["weather"][0]["description"];
var temp = obj["main"]["temp"];
var pressure = obj["main"]["pressure"];
var wind_speed = obj["wind"]["speed"];
var SearchResultsHTML = "City: " + city_name + "<br />" +
"Country: " + country_name + "<br />" +
"Weather: " + weather_description + "<br />" +
"Temperature: " + temp + "<br />" +
"Pressure: " + pressure + "<br />" +
"Wind Speed: " + wind_speed + "<br />";
$("#SearchResults").html(SearchResultsHTML);
}
}
var Firstbox = $("#Firstbox").val();
var Secondbox = $("#Secondbox").val();
var apiKey = "52453f34dee0d65b1a41a02656142c6b";
if (inputType==1) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?q=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType==2) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?zip=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType==3) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?lat=" + Firstbox + "&lon=" + Secondbox +
"&APPID=" + apiKey;
}
xhttp.open("GET", SearchString, true);
xhttp.send();
}
});
function checkValidity() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid && second.validity.valid) {
return true;
} else {
return false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="searchForm" method="POST" action="URL">
<h2>OpenWeatherMap Weather Search</h2>
Search by:<br/>
<input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
<input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
<input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
<br/>
<label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" value="Regina" />
<label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" value="ca" /> <br/>
<input id="SearchButton" type="button" value="Search" />
</form>
<h2>Search Results:</h2>
<h3>Raw Result Text</h3>
<p id="ResponseText"></p>
<h3>Parsed Results</h3>
<p id="SearchResults"></p>
you can change your checkvalidation like this
$(document).ready(function () {
var inputType = 1;
$("#Radio1").click(function() {
$("#lbl1").text("City Name:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
$("#Firstbox").attr({
"type" : "text",
"pattern" : "[a-zA-Z]{2,}",
"value" : "Regina",
"setCustomValidity" : "Must be 2 or more characters in length"
});
$("#Secondbox").attr({
"type" : "text",
"pattern" : "[a-zA-Z]{2}",
"value" : "ca",
"setCustomValidity" : "Must be 2 characters in length"
});
inputType = 1;
});
$("#Radio2").click(function() {
$("#lbl1").text("Postal Code:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
$("#Firstbox").attr({
"type" : "text",
"pattern" : "[A-Z][0-9][A-Z]",
"value" : "S4X",
"setCustomValidity" : "Must follow format: S4X"
});
$("#Secondbox").attr({
"type" : "text",
"pattern" : "[a-zA-Z]{2}",
"value" : "ca",
"setCustomValidity" : "Must be 2 characters in length"
});
inputType = 2;
});
$("#Radio3").click(function() {
$("#lbl1").text("Latitude:");
$("#lbl2").text("Longitude:");
$("#Firstbox").removeAttr("pattern");
$("#Secondbox").removeAttr("pattern");
$("#Firstbox").attr({
"type" : "number",
"min" : "-90",
"max" : "90",
"step" : "any",
"value" : "50.4",
"setCustomValidity" : "Must be betwen -90 and 90"
});
$("#Secondbox").attr({
"type" : "number",
"min" : "-180",
"max" : "180",
"step" : "any",
"value" : "-105.5",
"setCustomValidity" : "Must be betwen -180 and 180"
});
inputType = 3;
});
$("#SearchButton").click(function () {
var Validation = checkValidity();
if ((Validation==true)) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var SearchResponse = this.responseText;
document.getElementById("ResponseText").innerHTML = SearchResponse;
var obj = JSON.parse(SearchResponse);
var city_name = obj["name"];
var country_name = obj["sys"]["country"];
var weather_description = obj["weather"][0]["description"];
var temp = obj["main"]["temp"];
var pressure = obj["main"]["pressure"];
var wind_speed = obj["wind"]["speed"];
var SearchResultsHTML = "City: " + city_name + "<br />" +
"Country: " + country_name + "<br />" +
"Weather: " + weather_description + "<br />" +
"Temperature: " + temp + "<br />" +
"Pressure: " + pressure + "<br />" +
"Wind Speed: " + wind_speed + "<br />";
$("#SearchResults").html(SearchResultsHTML);
}
}
var Firstbox = $("#Firstbox").val();
var Secondbox = $("#Secondbox").val();
var apiKey = "52453f34dee0d65b1a41a02656142c6b";
if (inputType==1) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?q=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType==2) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?zip=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType==3) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?lat=" + Firstbox + "&lon=" + Secondbox +
"&APPID=" + apiKey;
}
xhttp.open("GET", SearchString, true);
xhttp.send();
}
});
function checkValidity() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
var a
if (first.validity.valid && second.validity.valid) {
alert('a');
return a=true;
} else {
return a=false;
}
return a
}
});
I'm trying to get my JSON file to show up on the page when I push a button, but for some reason code does not get the file.
When I press the button it should show 4 arrays.
var autotila = document.getElementById("autolista")
var nappi = document.getElementById("nappi");
nappi.addEventListener("click", function() {
var auto = new XMLHttpRequest();
auto.open('GET', 'cars.json');
auto.onload = function() {
var ourData = JSON.parse(auto.responseText);
lisaahtml(ourData);
};
auto.send();
});
function lisaahtml(data) {
var htmlpatka = "";
for (i = 0; i < data.lenght; i++) {
htmlpatka += "<p>" + data[i].manufacturer + "," + data[i].model + "," + data[i].price + "," + data[i].wiki + "</p>";
}
autotila.insertAdjacentHTML('beforeend', htmlpatka)
}
<button id="nappi" value="nappi" type="button">Paina</button>
<div id="autolista"></div>
{
"data" : [{
"manufacturer" : "Porsche",
"model" : "911",
"price" : 135000,
"quality" : [{
"name" : "overall",
"rating" : 3
},{
"name" : "mechanical",
"rating" : 4
},{
"name" : "powertrain",
"rating" : 2
},{
"name" : "body",
"rating" : 4
},{
"name" : "interior",
"rating" : 3
},{
"name" : "accessories",
"rating" : 2
}],
"wiki" : "http://en.wikipedia.org/wiki/Porsche_997"
}
}
Looks lie there is a typo:
for (i = 0; i < data.lenght; i++)
should be
for (i = 0; i < data.length; i++)
pass data.length
var autotila = document.getElementById("autolista")
var nappi = document.getElementById("nappi");
nappi.addEventListener("click", function() {
var auto = new XMLHttpRequest();
auto.open('GET', 'cars.json');
auto.onload = function() {
var ourData = JSON.parse(auto.responseText);
lisaahtml(ourData);
};
auto.send();
});
function lisaahtml(data) {
var htmlpatka = "";
for (i = 0; i < data.lenght; i++) {<<<----- data.length
htmlpatka += "<p>" + data[i].manufacturer + "," + data[i].model + "," + data[i].price + "," + data[i].wiki + "</p>";
}
autotila.insertAdjacentHTML('beforeend', htmlpatka)
}
Recently, I have been working on an piece of code that encrypts letters and decrypts them as long as the user has the proper, custom key. I worked out how to do it, but for every letter I want to add, I have to put:
if ( map.hasOwnProperty(input[0]) )
{
var _1 = map[input[0]]
}
Then at the end:
var encrypted = (_1 + _2 + _3 + _4 + _5 + _6 + _7 + _8 + _9 + _10 + _11 + _12 + _13 + _14 + _15 + _16 + _17 + _18 + _19 + _20 + _21 + _22 + _23 + _24 + _25 + _26 + _27 + _28 + _29 + _30 + _31 + _32 + _33 + _34 + _35 + _36 + _37 + _38 + _39 + _40 + _41 + _42 + _43 + _44 + _45 + _46 + _47 + _48 + _49 + _50 + _51 + _52 + _53 + _54)
For however many letters I put in.
A simplified version of the code with only 3 letters is this:
var map = {
"a" : "A",
"b" : "B",
"c" : "C",
"d" : "D",
"e" : "E",
"f" : "F",
"g" : "G",
"h" : "H",
"i" : "I",
"j" : "J",
"k" : "K",
"l" : "L",
"m" : "M",
"n" : "N",
"o" : "O",
"p" : "P",
"q" : "Q",
"r" : "R",
"s" : "S",
"t" : "T",
"u" : "U",
"v" : "V",
"w" : "W",
"x" : "X",
"y" : "Y",
"z" : "Z",
" " : " "
}
function main()
{
var input = prompt("Enter a character!");
var encrypted = -1;
if ( map.hasOwnProperty(input[0]) )
{
var _1 = map[input[0]]
}
if ( map.hasOwnProperty(input[1]) )
{
var _2 = map[input[1]]
}
if ( map.hasOwnProperty(input[2]) )
{
var _3 = map[input[2]]
}
var encrypted = (_1 + _2 + _3)
document.write(encrypted);
}
main()
(The map is just for simplicity, as it is a little more complicated in the full code)
Is there a way to have access to as many letters as I want to simplify the code?
You can use a loop for this kind of thing. Here is an example:
var map = {" " : " "};
for(var i = 0; i < 25; i++){
map[String.fromCharCode(97 + i)] = String.fromCharCode(65 + i);
}
function main() {
var input = prompt("Enter a character!");
var encrypted = "";
for(var i = 0; i < input.length; i++){
if(map[input[i]]){
encrypted += map[input[i]];
}
}
document.write(encrypted);
}
main();
I have an array which is in the following format:
RBS: [ {
"RegExp": "",
"Type": ""
} ],
PAN: [ {
"RegExp": "Date",
"Type": "Date"
} ]
Now I want to pass the value PAN to a method and it should get the count of PAN length 1 and get PAN of regex values and type value. How can I do this? I formed an array like this: Name holds RBS and PAN:
var Regexp = [];
RegExpr.push(Name + ":" + Regexp);
function Check(test) {
//test will be RBS /PAN
}
var obj = {
RBS:[{"RegExp":"","Type":""}],
PAN:[{"RegExp":"Date","Type":"Date"}]
};
function getTypeAndValue( obj, value )
{
var output;
var keys = Object.keys( obj );
if ( obj [value ] )
{
output = obj[ value ][ 0 ];
}
return output;
}
var value = getTypeAndValue( obj, "PAN" );
if ( value )
{
console.log( "type is " + value.Type + " and RegExp is " + value.RegExp );
}
else
{
console.log( "this value doesn't exists" );
}
You mean something like this?
HTML
<div id="count"></div>
<div id="detail"></div>
JAVASCRIPT
var countEl = document.getElementById("count");
var detailEl = document.getElementById("detail");
function Check(test){
var count = test.length;
countEl.innerHTML = "Count: " + count;
detailEl.innerHTML = "";
for (var i = 0 ; i < count ; i++){
var values = test[i];
detailEl.innerHTML +=
"<br/>" + (i +1) + ":<br/>" +
"RegExp: " + values["RegExp"] + "<br/>" +
"Type: " + values["Type"] + "<br/>";
}
}
var Name = {
RBS: [ {
"RegExp": "",
"Type": ""
} ],
PAN: [ {
"RegExp": "Date",
"Type": "Date"
} ]
};
Check(Name.PAN);
DEMO
Here's a JSFiddle.
So, I have this function.
function makeContent(jsonData) {
var aProperty,
containerType,
contentContainerName,
containerIdentifier,
containerComment,
theContent;
console.log("jsonData = ");
console.log(jsonData);
var madeContent;
for (aProperty in jsonData) {
console.log("Working on property " + aProperty);
console.log("With value of ");
console.log(jsonData[aProperty]);
switch (aProperty) {
case "containerType": {
containerType = jsonData[aProperty];
break;
}
case "contentContainerName": {
contentContainerName = jsonData[aProperty];
break;
}
case "containerComment": {
containerComment = jsonData[aProperty];
break;
}
case "containerIdentifier": {
containerIdentifier = jsonData[aProperty];
break;
}
case "itemContent": {
theContent = jsonData[aProperty];
break;
}
}
}
if (typeof theContent !== 'undefined') {
console.log("theContent =");
console.log(theContent);
if (theContent.hasOwnProperty) {
if (madeContent != 'undefined') {
madeContent = makeContent(theContent);
madeContent = "<" + containerType + " " + containerIdentifier + "=\"" + contentContainerName + "\">" + madeContent + "</" + containerType + ">" + containerComment;
}
} else {
madeContent = "<" + containerType + " " + containerIdentifier + "=\"" + contentContainerName + "\">" + theContent + "</" + containerType + ">" + containerComment
console.log(madeContent);
console.log("Else statement");
}
}
return madeContent;
}
My trouble doesn't start until after the recursive call. For some reason after I call the makeContent() again in a recursive way, in the for loop to go through the properties in the object, I get 0 for the aProperty.
The JSON Data:
{
"contentContainerName" : "footer-bgcontent",
"containerType" : "div",
"containerIdentifier" : "id",
"containerComment" : "<!-- End #footer-bgcontent-->",
"itemContent" : [
{
"contentContainerName" : "footer",
"containerType" : "div",
"containerIdentifier" : "id",
"contentComment" : "<!-- End #footer -->",
"itemContent" : [
{
"contentContainerName" : "footerLink",
"containerType" : "a",
"containerIdentifier" : "id",
"contentTag" : ""
},
{
"contentContainerName" : "footerContent",
"containerType" : "div",
"containerIdentifier" : "id",
"contentTag" : "<div id=\"footerContent\"></div><!-- End #footerContent-->",
"itemContent" : [
{
"contentContainerName" : "createdBy",
"containerType" : "p",
"containerIdentifier" : "id",
"contentTag" : "<p id=\"createdBy\"></p>",
"itemContent" : "Created by: Patrick McAvoy"
},
{
"contentContainerName" : "lastModified",
"containerType" : "p",
"containerIdentifier" : "id",
"contentTag" : "<p id=\"lastModified\"></p>",
"itemContent" : "Last Modified: "
},
{
"contentContainerName" : "copyright",
"containerType" : "p",
"containerIdentifier" : "id",
"contentTag" : "<p id=\"copright\"></p>",
"itemContent" : "Copright"
}
]
}
]
}
]
}
Then the output
jsonData =
footer.js:51
Object
footer.js:55Working on property contentContainerName
footer.js:56With value of
footer.js:57footer-bgcontent
footer.js:55Working on property containerType
footer.js:56With value of
footer.js:57div
footer.js:55Working on property containerIdentifier
footer.js:56With value of
footer.js:57id
footer.js:55Working on property containerComment
footer.js:56With value of
footer.js:57<!-- End #footer-bgcontent-->
footer.js:55Working on property itemContent
footer.js:56With value of
footer.js:57[
Object
]
footer.js:83theContent =
footer.js:84[
Object
]
footer.js:50jsonData =
footer.js:51[
Object
]
footer.js:55Working on property 0
footer.js:56With value of
footer.js:57
Object
footer.js:38Made content:
footer.js:39<div id="footer-bgcontent">undefined</div><!-- End #footer-bgcontent-->
I'm unsure if this is causing your problem, but this line is wrong:
if (theContent.hasOwnProperty)
.hasOwnProperty is a method of every object/type in JS, so the test above is always true and so your code will always recurse, even if .itemContent is a string.
In any event, the code is unnecessarily complicated - there's no need to iterate through all the properties and test each key - just assign them directly to the required variables!
I believe the below code replicates what you're trying to do and is much shorter!
function makeContent(data) {
var type = data.containerType || 'div',
name = data.contentContainerName || '',
id = data.containerIdentifier || 'id',
comment = data.containerComment || '',
content = data.itemContent || '';
if (Array.isArray(content)) {
content = content.map(makeContent).join('');
}
return '<' + type + ' ' + id + '="' + name + '">' + content +
'</' + type + '>' + comment;
}
where the || 'foo' ensures the strings are assigned default values if not specified.
See http://jsfiddle.net/alnitak/rmTTg/ - NB: this code does nothing with the contentTag proeprty which is also unused in your own code.