Javascript Need to pull a value from a function within an array - javascript

Here is my code:
<script>
window.addEvent('domready', function(){
new Request.Stocks({
stocks: ['SXCL'],
onComplete: function(yahoo){
var result = '';
Array.each(Array.from(yahoo.query.results.quote), function(quote){
result += '<div class="company-ticks"></div>
<span class="company">Steel Excel ({Name})</span>
<span class="sub-info"> - OTC Markets<span> </div> <div><span class="value">
{LastTradePriceOnly}</span><span class="changeup">
<img src="change-up.gif" class="change-img" />{Change}
({ChangeinPercent})</span></div></div>'.substitute(quote);
}, this);
$('stocks').set('html', result);
},
onRequest: function(script){
$('stocks').set('text', 'Loading...');
}
}).send();
// Request.Stocks.element.js
});
</script>
You see where I have the variable {Change]. I need to determine if this variable is a positive or negative value. If it is positive then it should display the class as "changeup" and the image as change-up.gif. If the value is negative then the class displayed should be "changedown" and the image would be change-down.gif
The images are a green arrow up and a red arrow down. The classes make the color altrenate between red and green.
Because this is within an array thats being called using a function I'm not sure how to go about this. I assume I would have to split up my "result" into 3 sections. The section before, the section that sets the class and the image, and then the rest of the result.
Any help would be appreciated.
This uses Javascript with mooTools. It's pulling a stock quote from yahoo.

I made the assumption that the Change variable was a property of the quote object. Otherwise that's an easy fix in the code bellow.
Array.each(Array.from(yahoo.query.results.quote), function (quote) {
quote.changeImage = (quote.Change > 0) ? 'change-up.gif' : 'change-down.gif';
result += '<div class="company-ticks"></div>
<span class="company">Steel Excel ({Name})</span>
<span class="sub-info"> - OTC Markets<span> </div> <div><span class="value">
{LastTradePriceOnly}</span><span class="changeup">
<img src="{changeImage}" class="change-img" />{Change}
({ChangeinPercent})</span></div></div>'.substitute(quote);
}, this);
Please note, producing HTML in the was you are doing is a bit risky and hard to maintain.

Related

Jquery Classes and InnerHtml

So what I'm doing is pulling battery voltage and the state of a battery from a Mysql database processing the data in data.php and putting that into a Json array all that is fine. When I get to the Javascript side I get stuck.
2 Questions:
Question 1: How do insert the value into id voltage in html without removing the span?
HTML Code:
<div id="voltState" class="tile-box bg-green">
<div class="tile-header">
Battery Status
<div class="float-right">
<i class="glyph-icon icon-bolt"></i>
Green
</div>
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-database"></i>
<div id="voltage" class="tile-content">
<span>volts</span>
</div>
</div>
</div>
Questions 2: class="tile-box bg-green"> I want to replace with the var status from the Javascript so it looks something like class="tile-box bg-(status var here)">
$(document).ready(function() {
sensorData();
});
function sensorData(){
$.ajax({
type:'GET',
url:"data.php",
data:"json",
success:function(sensor) {
//document.write(sensor);
var volt = sensor[0];
var status = sensor[1];
var date = sensor[2];
document.getElementById('voltage').innerHTML = (volt);
$("#voltState").toggleClass('bg-green bg-(STATUS VAR HERE??)');
},
dataType:'json'
});
}
setInterval(sensorData, 3000);
You can use $("#voltage").append(volt) or $("#voltage").prepend(volt) based on if you want the span before or after the value. In this case I assume you want the span after the volt so you can use the second code. If you would like the value inside a new span you can also use:
$("#voltage").prepend($("").text(volt));
You can store the previous status value in a variable lets say pastStatus. So once you have set
$("#voltState").removeClass('bg-'+pastStatus).addClass('bg-'+status);
pastStatus = status
Note: toggleClass is used when you want to switch between adding and removing the same class. It can't be used in this case since you want to add a class and remove another.
document.getElementById('voltage').appendChild(volt);
or
document.getElementById('voltage').innerHTML = '<span>'+volt+'</span>';

Hide and show spans with a specific class

I'm i'm trying to display songs made by an artist when i click the artist's name.
Here's my HTML
<div id="artists">
<span class="artist" id="Eminem" onclick="showSongs("Eminem")">Eminem</span>
</div>
<div id="songs">
<span style="display:none;" class="Eminem" id="Eminem - Survival" onclick="playSong('Eminem - Survival');">Survival</span>
</div>
And here is my Javascript
function showSongs(artist) {
document.getElementsByClassName(artist).styles.display="inline";
}
This is not all my code, I have more artists and more songs.
but the point is that i want the songs from an artist to display when i click the artists name
I have googled it for a while now, All i found was that i had to display span tags as inline.
If you need more information just ask and i'll edit the post
First, adjust the artist name you are sending to use single quotes, you are breaking the string by using double quotes.
<span class="artist" id="Eminem" onclick="showSongs('Eminem')">Eminem</span>
Then when you get elements by class name you are retrieving a collection and need to loop through them. Shown below:
function showSongs(artist) {
var elements = document.getElementsByClassName(artist);
for(var i = 0; i < elements.length; i++) {
elements[i].style.display="inline";
}
}
Here is a jsFiddle.
EDIT: Ah yes, see the other answers for the other half of the problem.
This code should work, the only thing I see wrong with it is this line:
<span class="artist" id="Eminem" onclick="showSongs("Eminem")">Eminem</span>
You should use single quotes inside the showSongs call:
<span class="artist" id="Eminem" onclick="showSongs('Eminem')">Eminem</span>
If that does not solve the problem, it is probably caused by some other code on the page.
getElementsByClassName returns an array-like collection. I don't think you can change the style this way.. Maybe you could try this :
function showSongs(artist) {
var artists = document.getElementsByClassName(artist);
for(var i = 0; i < artists.length; i++) {
artists[i].style.display="inline";
}
}
Would be a lot easier with jquery.
Here you go: http://jsfiddle.net/LVRGZ/3/
<div id="artists">
<span class="artist" onclick="showSongs('Eminem')">Eminem</span>
</div>
<div id="Eminem" style="display:none;">
<span id="Eminem - Survival" onclick="playSong('Eminem - Survival');">Survival</span><br/>
<span id="Another Song" onclick="playSong('Eminem - 2');">Another Song</span><br/>
<span id="A Third Song" onclick="playSong('Eminem - 3');">A Third Song</span><br/>
</div>
<script>
showSongs=function(id) {
alert("Showing "+id);
document.getElementById(id).style.display='';
}
</script>

Easy way to replace parts of code with other parts of code

I'm making a small website for a game called League of Legends that compares matchup data (what champion counters a certain champs counters) and prints out results on a webpage. I'm using this html code that shows character portraits with onClick() to make them start a function when clicked
<a href="#" onClick="tristanaweak()"><img src="portraits/Aatrox_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Ahri_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Akali_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Alistar_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Amumu_Square_0.png" width="25px" height="25px" alt=random></img>
I've already manually put in the picture filenames (which was very tedious), but I still have to rename the onclick() values (tristanaweak) with the champion name (aatroxweak, ahriweak, etc.). I was thinking of doing this with a loop that edits text, but I don't know how I would go about doing this.
I'm fairly new to using Javascript, is there an easy way to rename all the onClick="tristanaweak()"'s in the html code to the first part of the png filenames in the same lines?
You can do this using PHP. First, create a list of all the champions:
$champs = "aatrox,arhi,akali,alistar,amumu,...";
Then do an explode to separate each champion and store it as an element in an array:
$pieces = explode(",", $champs);
echo $pieces[0]; //this will return aatrox
echo $pieces[1]; //this will return ahri
Now you can use a for loop to echo the desired results:
for($i=0;$i<count($pieces);$i++) {
echo '<!--other stuff here-->';
}
In the end, the result will be something like this:
<!--other stuff here-->
<!--other stuff here-->
etc, etc. I hope this is what you are looking for.
You should chose a different approach in my opinion. In javascript, you can also generate HTML dynamically using javascript function document.createElement(string tagName).
So, one of two possible soulitions would be creating a new images with new event for every champion:
HTML:
<div id="hero_images">
</div>
JS:
var champions = [
{
name: "Veigar",
callback: function() {/**Whatever you wanna do in onclick**/}
},
{
name: "Vladimir",
callback: function() {/**Whatever you wanna do in onclick**/}
},
{
name: "Morgana",
callback: function() {/**Whatever you wanna do in onclick**/}
}
];
//Now lets make an image for every champion:
var container = document.getElementById("hero_images"); //We'll put images in div I've defined in HTML above
for(var i=0; i<champions.length; i++) { //Loop through "champions" which is an array
var a = document.createElement("a");
a.href="#";
a.onclick = champions[i].callback; //Assign function from champion list to this <a>
//Also create the image
var img = document.createElement("img");
img.src = "portraits/"+champions[i].name+"_Square_0.png"; //I suppose image always have champion name in beginning
img.alt = champions[i].name; //Alternative text for no-image users
//Append image to link:
a.appendChild(img);
//Append <a> to <div>
contained.appendChild(a);
}
But in fact, you should use a global function for champions and you should have champion stats defined in the champions I've used. Under such circumstances:
var champions = [
{
name: "Veigar",
stats: {
inteligence: 666,
strength: 1,
/*..whatever you use...**/
}
}
];
for(/**imagine the prewious code here**/) {
...
a.onclick=(function(i) {
ShowHeroStatsOrWhatever(champions[i]);
})(i);
...
}
function ShowHeroStatsOrWhatever(champion) {
alert("Champions intelligence is "+champion.stats.inteligence);
}
Have you played around with jQuery .replaceWith();?
Description: Replace each element in the set of matched elements with
the provided new content and return the set of elements that was
removed.
Or the straight up javascript way (which I use with in conjunction with jQuery over the above 90% of the time) with .replace();
The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.

How do i get a value from Kendo UI template

I have this template:
var template = kendo.template("<div class='relatedItemRow'>"
+ "<span id='relatedItemName'>Related Item #: Number #</span>"
+ "<div class='relatedItemRowInfo'><span >#: Name #</span>"
+ "<a data-relatedItemID='#: Value #' class='removeRelatedItem'>"
+ "<img src= '#: Img #'/</a></div><br class='clear'/></div>");
var data = {
Name: "" + checkbox.getAttribute('flatName'),
Number: $('#relatedItemsList').children().length + 1,
Img: '/Content/images/x_remove.png',
Value: checkbox.value
};
var result = template(data);
$("#relatedItemsList").append(result);
I am able to access the data-relatedItemID by using:
$('#relatedItemsList').children().eq(i).children().last().attr('data-relatedItemID')
But how do I get to the Number field in data? I want to change that one dynamically.
I have tried:
$('#relatedItemsList').children().eq(i).children().attr('Number') == 5
but it does not work. Any idea how to do that?
I know that there is an answer for this question even accepted but I'd like to suggest a different approach that I think it is much simpler and more Kendo UI oriented and is using Kendo UI ObservableObject. This allows you to update an HTML that is bound to the ObservableObject without having to crawl the HTML.
This approach is as follow:
Wrap your data definition with a Kendo Observable Array initialization.
Redefine your template and start using using data-binding.
Append this new template to your HTML.
Bind data to the HTML.
Now you can get current value using data.get("Number") or set a new value using data.set("Number", 5) and the HTML get magically updated.
The code is:
Template definition
<script type="text/kendo-template" id="template">
<div class='relatedItemRow'>
<span id='relatedItemName'>Related Item <span data-bind="text : Number"></span></span>
<div class='relatedItemRowInfo'>
<span data-bind="html : Name"></span>
<a class='removeRelatedItem' data-bind="attr: { data-relatedItemID : Value }">
<img data-bind="attr : { src : Img }"/>
</a>
</div>
<br class='clear'/>
</div>
</script>
data definition as:
var data = new kendo.data.ObservableObject({
Name: "" + checkbox.getAttribute('flatName'),
Number: $('#relatedItemsList').children().length + 1,
Img: '/Content/images/x_remove.png',
Value: checkbox.value
});
and the initialization of the HTML is:
$("#relatedItemsList").append($("#template").html());
Getting current value of Number is:
var old = data.get("Number");
Setting is:
data.set("Number", 5);
Running example in JSFiddle here : http://jsfiddle.net/OnaBai/76GWW/
The variable "result" and thus the data you're trying to change aren't a Kendo templates, they're just html created by the template, and the number is just text in the html. To modify the number without rebuilding the whole string, you need to change the template so you can select the number by itself with jQuery by putting it in it's own element, and adding something to identify it.
var template = kendo.template("<div class='relatedItemRow'><span id='relatedItemName'>Related Item <span class='relatedNumberValue'>#: Number #</span></span><div class='relatedItemRowInfo'><span >#: Name #</span><a data-relatedItemID='#: Value #' class='removeRelatedItem'><img src= '#: Img #'/</a></div><br class='clear'/></div>");
//other code the same
And once you can select it, then you can change it like this.
$('#relatedItemsList').children().eq(i).find('.relatedNumberValue').text(5);
And retrieve it like this.
var foo = $('#relatedItemsList').children().eq(i).find('.relatedNumberValue').text();

Loading specific div based on the results of multiple dropdowns

EDIT: Would the approach be much easier if the Javascript listed was removed completely, and the dropdown menus restyled as <div>'s within <li>'s, and the final div was generated by a Javascript onclick event? e.g.
<a id="click_link">click me</a>
$("#click_link").click(function(){
$('#div').load('http://www.link.com/');
});
Either way, the problem at hand...
My decision to use an elegant-looking javascript solution is highlighting my massive inexperience when it comes to javascript! The problem is, on the face of it, simple...
Once an option has been chosen on each of the dropdown menus, I need a final div to load so that a specific button can be shown (a link to buy the item with the specified options, e.g. choosing Necklace D, with Stone Option B, and Delivery Option A = loading div with 'Buy' Button #17)
The dropdowns are divs that are filled and styled through the Javascript (as opposed to using the simpler <form> and <input> method), giving the flexibility to add two lines of differently styled text for each option etc. - This is where I step into the realm of the unknown and my inexperience shines through.
The isolated section is viewable in its entirity here
Ok, to the code.
Here's the Javascript:
function createByJson() {
var pearlData = [
{description:'Choose your pearl...', value:'Pearls', text:'Pearls'},
{description:'Beautiful black stone', value:'Black Pearl', text:'Black Pearl'},
{description:'Classic white stone', value:'White Pearl', text:'White Pearl'}
];
$("#DropItPearls").msDropDown({byJson:{data:pearlData, name:'pearls', width: 200}}).data("dd");
var blodeuweddData = [
{description:'Choose your item...', value:'Blodeuwedd', text:'the Blodeuwedd Collection'},
{description:'A striking statement', value:'BlodeuweddCelticStatement', text:'Celtic Statement Piece'},
{description:'Gold laced flower and pearl', value:'BlodeuweddBracelet', text:'Bracelet'},
];
$("#DropItBlodeuwedd").msDropDown({byJson:{data:blodeuweddData, name:'blodeuwedd', width: 250}})
.msDropDown({on:{change:function(data, ui) {
var val = data.value;
if(val!="")
window.location = val;
}}}).data("dd");
var deliveryData = [
{description:'Choose your method...', value:'Delivery', text:'Delivery Options'},
{description:'4-6 weeks delivery', value:'Four Weeks', text:'Made To Order'},
{description:'(unavailable on this item)', value:'Rush', text:'Express Delivery', disabled:true}
];
$("#DropItDelivery").msDropDown({byJson:{data:deliveryData, name:'delivery', width: 200, selectedIndex: 1}}).data("dd");
paymentData = [
{ description:'How would you like to pay?', value:'Payment', text:'Payment Method'},
{image:'images/msdropdown/icons/Visa-56.png', description:'Secure online payment', value:'Visa', text:'Visa'},
{image:'images/msdropdown/icons/Paypal-56.png', description:'Secure online payment', value:'Paypal', text:'Paypal'},
{image:'images/msdropdown/icons/EmailPay-56.png', description:'Order by email', value:'Email Payment', text:'Send Your Details'},
{image:'images/msdropdown/icons/Mastercard-56.png', description:'(coming soon)', value:'Mastercard', text:'Mastercard', disabled:true},
{image:'images/msdropdown/icons/Collect-56.png', description:'(coming soon)', value:'Collection', text:'Order and Collect', disabled:true},
{image:'images/msdropdown/icons/Email-56.png', description:'email Menna', value:'Other Method', text:'Alternatives'}
];
$("#DropItPayments").msDropDown({byJson:{data:paymentData, name:'payments', width: 250}}).data("dd");
}
$(document).ready(function(e) {
//no use
try {
var pages = $("#pages").msDropdown({on:{change:function(data, ui) {
var val = data.value;
if(val!="")
window.location = val;
}}}).data("dd");
var pagename = document.location.pathname.toString();
pagename = pagename.split("/");
pages.setIndexByValue(pagename[pagename.length-1]);
$("#ver").html(msBeautify.version.msDropdown);
} catch(e) {
//console.log(e);
}
$("#ver").html(msBeautify.version.msDropdown);
//convert
$("select").msDropdown();
createByJson();
$("#tech").data("dd");
});
function showValue(h) {
console.log(h.name, h.value);
}
$("#tech").change(function() {
console.log("by jquery: ", this.value);
})
//
And the html:
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Item</p></div>
<div id="DropItBlodeuwedd"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Precious Stones</p></div>
<div id="DropItPearls"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Payment</p></div>
<div id="DropItPayments"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Delivery</p></div>
<div id="DropItDelivery"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Buy Now!</p></div>
<div id="DropItBuy"></div>
</div>
Again, working version viewable here
Many thanks in advance!
What I think you want is for your Buy button to dynamically read what the dropdowns currently say and build a link for redirection based on that, rather than trying to update the Buy button every time a dropdown changes.
From your code I can't see what the form of the final URL is supposed to be. For example, to get the current value of the delivery option, you can check $('#DropItDelivery :selected').text() which will be something like "Made To Order".
Your Buy Now! could be a button with a click event that reads these values and constructs the URL with basic string concatenation, e.g.:
window.location = "buynow.html?delivery=" + $('#DropItDelivery :selected').text() +
"&payment=" + $('#DropItPayments :selected').text()
// etc.
Of course you'd have to handle these options on the server.
In case you want to redirect to the payment page of the processor, you can just branch based on the payment method and give them the URL you want based on that.
var pm = $('#DropItPayments :selected').text();
if (pm == "Visa")
{
// Visa payment URL construction
}
else if (pm == "Send Your Details")
{
// Send your details URL construction
}
// etc.

Categories

Resources