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
}
});
Related
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)
}
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",
};
I am receiving the follow error in my Console :
" Uncaught TypeError: undefined is not a function "
<script>
//name : calculateResult()-->
function calculateResult() {
console.log("calculateResult() function called!");
//1. Declare Variables-->
var hoursWorked,
jobCategory,
jobCategorySelectedIndex,
hoursEligibleForBasePay,
hoursEligibleForOvertime,
basePayAmount,
overtimePayAmount,
totalPayAmount,
overtimePayRate;
//2. Values for Local Variables-->
hoursWorked = document.getElementById("txthoursWorked").value;
console.log("hoursWorked = " + hoursWorked);
//Get Select element choice: Job Category-->
jobCategorySelectedIndex = document.getElementById("seljobCategory").selectedIndex;
console.log("jobCategorySelectedIndex = " + jobCategorySelectedIndex);
jobCategory = document.getElementById("seljobCategory").options[jobCategorySelectedIndex].value;
console.log("jobCategory = " + jobCategory);
//3. Do Calculations-->
hoursWorked = parseFloat(hoursWorked);
if (jobCategory == "M") {
basePayRate = "25";
} else if (jobCategory == "R") {
basePayRate = "20";
} else if (jobCategory == "S") {
basePayRate = "15";
}
hoursEligibleForBasePay = 40;
basePayAmount = basePayRate * hoursEligibleForBasePay;
console.log("basePayAmount = " + basePayAmount);
console.log("hoursEligibleForOvertime =" + hoursEligibleForBasePay);
if (hoursWorked > 40) {
hoursEligibleForOvertime = hoursWorked - 40;
} else {
hoursEligibleForOvertime = 0;
}
console.log("hoursEligibleForOvertime = " + hoursEligibleForOvertime);
overtimePayRate = 1.5 * basePayRate;
overtimePayAmount = overtimePayRate * hoursEligibleForOvertime;
totalPayAmount = basePayRate + overtimePayAmount;
console.log("overtimePayRate = " + overtimePayRate);
console.log("overtimePayAmount = " + overtimePayAmount);
console.log("totalPayAmount = " + totalPayAmount);
//4. Display Results-->
displayString = "Base Pay " + "$" + basePayAmount.toFixed(2) + "<br />" +
"Overtime Pay " + "$" + overtimePayAmount.toFixed(2) + "<br />"
"Total Pay " + "$" + totalPayAmount.toFixed(2);
document.getElementById("divDisplay").innerHTML = displayString;
}
</script>
the error is in the display string on the Total PayAmount line
any ideas?
The actual error is not actually on that line.
totalPayAmount is defined here:
totalPayAmount = basePayRate + overtimePayAmount;
basePayRate is defined here:
if (jobCategory == "M") {
basePayRate = "25";
} else if (jobCategory == "R") {
basePayRate = "20";
} else if (jobCategory == "S") {
basePayRate = "15";
}
So basePayRate is a string. Then totalPayAmount is also a string, which would not have a toFixed method.
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.
This program right now reads in xml code, gets a stock abbreviation, alphabetically sorts them, and then prints them out in an uo list. If you hover over the abbreviations the color will change to red. The goal I'm having is when you hover over an abbreviation, it will show all the data from the xml data just for that company. I tried using the if statement saying if the symbol (abbreviation in xml file) is equivalent to the name (abbreviation in array) then it prints out all the junk for it. The line that prints everything out works correctly in the format I want. I just need to work on the if statement.
What I have figured out is I cannot compare two variables with the ==. Keep in mind symbol is an attribute as well, and name is from an array that stores the symbols. I also tried just saying - if(checkPassword(name, symbol)) - and print it all out as I did in the jQuery code below, but that did not work.
I put a comment next to the if statement I am working on, it's towards the bottom of the jQuery.
HTML:
<body onload="onBodyLoad()">
<div id="stockList"></div>
<br />
<br />
<br />
<div id="stockInfo"></div>
jQuery:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "stocks.xml",
dataType: "xml",
success: function (xml) {
var companyNames = [];
$(xml).find('Stock').each(function () {
var symbol = $(this).attr('symbol');
companyNames.push(symbol);
});
companyNames.sort();
$.each(companyNames, function (index, name) {
$('#stockList').append('<div><li>' + name + '</li></div>');
});
function CheckPassword(val, val2) {
var strInput = val.value;
var strInput2 = val2.value;
if (strInput != strInput2) {
val2.focus();
val2.select();
return false;
} else
return true;
}
$(xml).find('Stock').each(function () {
var company = $(this).find('Company').text();
var symbol = $(this).attr('symbol');
var market = $(this).find('Market').text();
var sector = $(this).find('Sector').text();
var price = $(this).find('Price').text();
var low = $(this).find('Low').text();
var high = $(this).find('High').text();
var amount = $(this).find('Amount').text();
var yieldx = $(this).find('Yield').text();
var frequency = $(this).find('Frequency').text();
$('*').mouseover(function () {
$('#stockList li').text($(this).attr('comparison'));
});
$('#stockList li').hover(
function () {
$(this).css({ color: 'red' }); //mouseover
if (name == symbol) { // THIS IS THE STATEMENT YOU'RE LOOKING FOR PROGRAMMING GODS
$('#stockInfo').append('<div><ol><li>' + "Company = " + company + '</li><br/><li>' + "Market = " + market + '</li><br/><li>' + "Sector = " + sector + '</li><br/><li>' + "Price = " + price + '</li><br/><li>' + "Year Range = " + low + " " + high + '</li></ol><br/>');
}
},
function () {
$(this).css({ color: 'navy' }); // mouseout
$('#stockInfo').empty();
}
);
});
}
});
});
XML sample:
<Products>
<Stock symbol="GOOG">
<Company>Google</Company>
<Market>NASDAQ</Market>
<Sector>Software</Sector>
<Price>$487.80</Price>
<YearRange>
<Low>$331.55</Low>
<High>$488.50</High>
</YearRange>
<Dividend available="false"/>
</Stock>
<Stock symbol="BA">
<Company>Boeing Company</Company>
<Market>NYSE</Market>
<Sector>Aerospace</Sector>
<Price>$79.05</Price>
<YearRange>
<Low>$63.70</Low>
<High>$89.58</High>
</YearRange>
<Dividend available="true">
<Amount>$1.20</Amount>
<Yield>$1.50</Yield>
<Frequency>QTR</Frequency>
</Dividend>
</Stock>
<Stock symbol="MO">
<Company>Altria Group</Company>
<Market>NYSE</Market>
<Sector>Comsumables</Sector>
<Price>$81.70</Price>
<YearRange>
<Low>$68.36</Low>
<High>$85.00</High>
</YearRange>
<Dividend available="true">
<Amount>$3.44</Amount>
<Yield>$4.2</Yield>
<Frequency>ANNUAL</Frequency>
</Dividend>
</Stock>
</Products>
var companyData = [];
$(xml).find('Stock').each(function () {
var symbol = $(this).attr('symbol');
companyNames.push(symbol);
companyData[symbol] = {
company: $(this).find('Company').text(),
symbol: $(this).attr('symbol'),
market: $(this).find('Market').text(),
sector: $(this).find('Sector').text(),
price: $(this).find('Price').text(),
low: $(this).find('Low').text(),
high: $(this).find('High').text(),
amount: $(this).find('Amount').text(),
yieldx: $(this).find('Yield').text(),
frequency: $(this).find('Frequency').text()
};
});
...
$("#stocklist li").hover(function() {
$(this).css({ color: 'red' }); //mouseover
var info = companyData[$(this).text()];
$('#stockInfo').append('<div><ol><li>' + "Company = " + info.company + '</li><br/><li>' + "Market = " + info.market + '</li><br/><li>' + "Sector = " + info.sector + '</li><br/><li>' + "Price = " + info.price + '</li><br/><li>' + "Year Range = " + info.low + " " + info.high + '</li></ol><br/>');
});