How can I compare these strings in jQuery? - javascript

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/>');
});

Related

Select index Array with Drag & Drop

Good Day, I have this HTML:
<ul class="sortable-list" style="list-style-type: none;"></ul>
and this Javascript:
$(document).ready(function() {
var old, manip;
function Person(id, first, last, age, eyecolor) {
this.id = id;
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.display = function() {
sortableList.push(this);
$(".sortable-list").sortable({
axis: "y",
containment: ".sortable-list",
revert: true,
start: function(event, ui) {
var updt = ui.item.index();
manip = updt;
old = sortableList[manip];
},
update: function(event, ui) {
var newIndex = ui.item.index();
sortableList.splice(manip, 1);
sortableList.splice(newIndex, 0, old);
}
});
var moveMe = "<i class='fa fa-arrows-v' aria-hidden='true' style='border:1px solid black;padding:5px;background-color:#91DAF2;'></i>";
var seeDetails = "<i class='fa fa-eye' aria-hidden='true' style='border:1px solid black;padding:5px;background-color:#F5940C;' onclick='seeDetails(" + this.id + ");'></i>";
var fNameObj = "<input type='text' value=" + this.firstName + " size='7' style='font-size:13px;' disabled=true>";
var lNameObj = "<input type='text' value=" + this.lastName + " size='7' style='font-size:13px;' disabled=true>";
var ageObj = "<input type='text' value=" + this.age + " size='3' style='font-size:13px;' disabled=true>";
var output = "<li>" + moveMe + " " + seeDetails + " " + fNameObj + " " + lNameObj + " " + ageObj + "</li>";
$(".sortable-list").append(output);
};
var me = new Person(1, "John", "Doe", 22, "blue");
me.display();
var you = new Person(2, "Jane", "Smith", 33, "green");
you.display();
var him = new Person(3, "Mike", "Jones", 44, "brown");
him.display();
var her = new Person(4, "Gill", "Greer", 55, "green");
her.display();
var us = new Person(5, "Paul", "Mall", 66, "blue");
us.display();
});
var sortableList = [];
function seeDetails(index) {
var temp = sortableList[index - 1];
alert(temp.firstName + " " + temp.lastName + " has " + temp.eyeColor + " eyes.");
console.log(sortableList);
}
I use FontAwesome to display the icons for the buttons.
What I try to do is to display the content of the object by passing the id to the function seeDetails.
I'd like to keep track of the elements order, because I'll use it further in my code.
Is there any way to use that code to display the proper content of the object, after drag&drop ? Anybody can help ? Thanks!
JSFIDDLE
Sortable has 2 methods that may help: serialize and toArray
serialize
Serializes the sortable's item ids into a form/ajax submittable string. Calling this method produces a hash that can be appended to any url to easily submit a new item order back to the server.
It works by default by looking at the id of each item in the format "setname_number", and it spits out a hash like "setname[]=number&setname[]=number".
See more: http://api.jqueryui.com/sortable/#method-serialize
toArray
Serializes the sortable's item id's into an array of string.
See More: http://api.jqueryui.com/sortable/#method-toArray
Depending on how you want to use the order later, one of these methods will help you. I suspect you will want to pass this data into a variable in update or stop callback.
To ensure these work better, you would want to add an id attribute to opit list items. For example:
var output = "<li id='person-" + this.id + "'>" + moveMe + " " + seeDetails + " " + fNameObj + " " + lNameObj + " " + ageObj + "</li>";
What I noticed is that we're passing back an index to seeDetails(), when you can also pass back the id for that person. Consider this:
function seeDetails(i) {
var temp;
$.each(sortableList, function(k, p) {
if (p.id == i) {
temp = p;
}
});
console.log(temp.firstName, temp.lastName, "has", temp.eyeColor, "eyes.");
}
Putting it all together, here is what I would advise: https://jsfiddle.net/Twisty/Lyotc8d5/
JavaScript
$(document).ready(function() {
var old, manip;
function Person(id, first, last, age, eyecolor) {
this.id = id;
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.display = function() {
sortableList.push(this);
var that = this;
$(".sortable-list").sortable({
axis: "y",
containment: ".sortable-list",
revert: true,
start: function(event, ui) {
var updt = ui.item.index();
manip = updt;
old = sortableList[manip];
},
update: function(event, ui) {
var newIndex = ui.item.index();
sortableList.splice(manip, 1);
sortableList.splice(newIndex, 0, old);
}
});
var moveMe = $("<i>", {
class: 'fa fa-arrows-v',
"aria-hidden": true,
style: 'border:1px solid black;padding:5px;background-color:#91DAF2;'
});
var detailsBtn = $("<i>", {
class: 'fa fa-eye',
"aria-hidden": true,
style: 'border:1px solid black;padding:5px;background-color:#F5940C;'
}).click(function(e) {
seeDetails(that.id);
});
var fNameObj = $("<input>", {
type: 'text',
value: that.firstName,
size: 7,
style: 'font-size:13px;',
disabled: true
});
var lNameObj = $("<input>", {
type: 'text',
value: that.lastName,
size: 7,
style: 'font-size:13px;',
disabled: true
});
var ageObj = $("<input>", {
type: 'text',
value: this.age,
size: 3,
style: 'font-size:13px;',
disabled: true
});
var output = $("<li>", {
id: 'person-' + that.id
});
output.append(moveMe, detailsBtn, fNameObj, lNameObj, ageObj);
$(".sortable-list").append(output);
};
var me = new Person(1, "John", "Doe", 22, "blue");
me.display();
var you = new Person(2, "Jane", "Smith", 33, "green");
you.display();
var him = new Person(3, "Mike", "Jones", 44, "brown");
him.display();
var her = new Person(4, "Gill", "Greer", 55, "green");
her.display();
var us = new Person(5, "Paul", "Mall", 66, "blue");
us.display();
});
var sortableList = [];
function seeDetails(i) {
var temp;
$.each(sortableList, function(k, p) {
if (p.id == i) {
temp = p;
}
});
console.log(temp.firstName, temp.lastName, "has", temp.eyeColor, "eyes.");
}
A few small updates. Not that your code was wrong or incorrect, I just like creating the jQuery objects and find them easier to work with. Assigning this to variable that is helpful to ensure there is no confusion around this in other functions, like for click callback.

How to concatenate strings without using eval?

How do I concatenate these strings to get value from a variable. I want to avoid eval as so many of you are not keen on its use.
function getLesson() {
var lesson = "lesson" + localStorage.lessonNGS;
document.getElementById("lessonNumber").innerHTML = "Lesson " + (eval(lesson + "." + number));
document.getElementById("lessonTitle").innerHTML = (eval(lesson + "." + title));
document.getElementById("lessonScore").src = (eval(lesson + "." + score));
document.getElementById("mp3").src = (eval(lesson + "." + trackmp3));
document.getElementById("ogg").src = (eval(lesson + "." + trackogg));
document.getElementById("lessonTrack").load();
}
This works but I'm told it will cause me conflicts in some browsers.
Simply remove the eval
// Demo data
localStorage.setItem("lessonNGS",1);
var lesson1 = {
number: "1",
title: "Quarter Notes",
score: "scores/01_quarternotes.jpg",
trackmp3: "tracks/mp3/01_quarternotekeyexercises.mp3",
trackogg: "tracks/ogg/01_quarternotekeyexercises.ogg"
};
function getLesson() {
debugger;
var lesson = window["lesson" + localStorage.lessonNGS];
document.getElementById("lessonNumber").innerHTML = "Lesson " + lesson.number;
document.getElementById("lessonTitle").innerHTML = lesson.title;
document.getElementById("lessonScore").src = lesson.score;
document.getElementById("mp3").src = lesson.trackmp3;
document.getElementById("ogg").src = lesson.trackogg;
document.getElementById("lessonTrack").load();
}
Javascript String.prototype.concat():
str.concat(string2, string3[, ..., stringN])
Example:
var hello = 'Hello, ';
console.log(hello.concat('Kevin', ' have a nice day.'));

add javaScript array in another array

i got javaScript array hold elements records with unique elementIndex in it now what I have to add single or multiple components in same javaScript array for that particular element (same elementIdex).
this array can have as many elements as required and each element may have one or multiple components associated to that element.
I have managed to do first part, how i do second part ... that is add components records associated to single element.
note element and component are in separate javaScript function but i have global array
this is what i want to achieve (may be JSON)
QualificationElemenetsAndComponents[0] = {
Element [
ElementIndex : "",
ElementMarkingSchemeTitle : "",
ElementAvailableMark: "",
ElementPassMark: "",
ElementDistinctionMark: "",
Component[0]= [
componentIndex="",
componentMark =""
],
Component[1]= [
componentIndex="",
componentMark =""
],
Component[2]= [
componentIndex="",
componentMark =""
],
}
global array
var selectedComponentList = [];
var selectElementList = [];
element
$("#ElementTable").on("click", ".k1-grid-confirm", function () {
var E_RecordId = $(this).data("id");
var E_MarkingSchemeTitle = $("#" + E_RecordId + "_EMST").val();
var E_AvailableMark = $("#" + E_RecordId + "_AM").val();
var E_PassMark = $("#" + E_RecordId + "_PM").val();
var E_MeritMark = $("#" + E_RecordId + "_MM").val();
var E_DistinctionMark = $("#" + E_RecordId + "_DM").val();
alert("elementRecordId " + E_RecordId + " E_MarkingSchemeTitle " + E_MarkingSchemeTitle + " E_AvailableMark " + E_AvailableMark + " E_PassMark " + E_PassMark + " E_MeritMark " + E_MeritMark + " E_DistinctionMark " + E_DistinctionMark);
//add data to array//
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark });
}
});
Component
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMark = $("#" + recordId + "_CM").val();
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });
//push array to Selected Element
?????????????????????????????????????
}
});
Many thanks
Define a function to refresh the global list:
// Elements
selectElementList.push({...});
refreshGlobalList();
// Components
selectedComponentList.push({...});
refreshGlobalList();
And the function:
var globalList = [];
function refreshGlobalList() {
globalList = selectElementList.concat(selectedComponentList);
}
arrayNum.push.apply(arrayNum, arrayValuTwo);
arrayNum.push.apply(arrayNum, arrayValuThree);
you can try this or you can try this
arrayNumber.push.apply(arrayNumber, arrayValueTwo.concat(arrayValueThree));

JQuery access some JSON data

I've been working on this for like an hour now, but can't seem to figure it out.
The JSON response:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
This seems to be correct, now the jquery:
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
The console.log("this.lastDate = " + this.lastDate); works, so does the one for this.lastId. this.response also works and nicely shows an array starting with index 0 and when expanded it you can see all elements in the developer view.
Now comes the part I cannot seem to understand: At the foreach over this.response it does not print anything useful (except Prototype skeleton) for this.
How can I access the values?
this.response.each(new function() {
This line is wrong. It should be:
this.response.forEach(function() {
P.S. I suggest doing $.each(json, function(){ instead of $(json).each(function() {.

Javascript Value Check

I'm writing a script that parses an XML file and displays it in html. Here it is:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("A: " + date + "<br />B: " + amount + " ISK<br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
I want to modify the output of "document.write", so that if the value "amount" is positive, enter the word "green", otherwise, if negative, enter the word "red". I tried to write it as follows:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("<script> if (amount >= 0) { document.write("green"); } else{ document.write("red"); } </scri" + "pt>");
});
});
</script>
But in that piece, I get a syntax error in "document.write". What I have written wrong and how could fix it?
I think you can compute the color before writing the output with document.write.
Something like this should work:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
var color = "green";
if (amount < 0) {
color = "red";
}
document.write("A: " + date + "<br />B: <span style='color:" + color + "'>" + amount + " ISK</span><br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
(syntax unchecked)
To get an answer just look, how this code is highlighted. The words 'green' and 'red' are outside the quotes. You should use single quotes (or escape the double quotes).
The other question is why do you use metaprogramming for such a simple task. Just write a condition with two different document.write statements.
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write(amount >= 0 ? "green" : "red");
});
});
</script>

Categories

Resources