I want to use the jQuery function .each() to apply a possible change to a value.
I have a bunch of labels in tags with a class="temp". If I have a switch to switch between Celsius and Fahrenheit I would like to update all html elements with the temp class. I will retrieve the value from the span, then update the span to have the new temperature.
Span tags look like
<span class="temp" id="holder_1443531366" style="text-align:center; display:inline-block;"><span style>86.1</span>
<span style="padding-left:3px;">°F</span>
</span>
Im sure this isnt the best looking html element, i didnt make it, im using a website to build a web dashboard and cannot actually change these directly.
There is other parts to this code, but I just need the main part working.
//Find all elements with span class="temp"
var temps = [];
var html;
var pHtml;
temps = jQuery('.temp').toArray();
html = jQuery('.temp').html();
//pHtml = jQuery('.temp').parseHTML();
if(temps != null){
console.log("Temps -> "+temps.length);
console.log("html -> "+html);
for(var i = 0; i < temps.length; i++){
console.log(temps[i]);
}
}else {
console.log("No temps found");
}
I have currently two elements to find and this is the output so far
Attempting to find temp classes
Temps -> 2
html -> <span style="">86.0</span><span style="padding-left:3px;">°F</span>
<span class="temp" id="holder_1443531366" style="text-align:center; display:inline-block;"><span style>86.1</span><span style="padding-left:3px;">°F</span></span>
<span class="temp" id="holder_1443531376" style="text-align:center; display:inline-block;"><span style>85.38</span><span style="padding-left:3px;">°F</span></span>
I save each element with the ".temp" class, find the temp (86.1) and then use that value to execute my temp converter function (or just some math right there).
With the new value, I will update the element from 86.1 -> the Celsius temp i just calculated.
what this code does, is that on click of the link, it cycles through each element with class .temp and gets the .degrees, converts that to Celsius, and then changes the F to a C.
i added classes on both spans to accomplish this (.degrees and .degType)
$(document).ready(function() {
$('.toC').on('click', function() {
$('.temp').each(function() {
var degrees = $(this).find('.degrees').html();
var cTemp = (parseFloat(degrees - 32) * (parseFloat(5/9))).toFixed(1);
$(this).find('.degrees').html(cTemp);
$(this).find('.degType').html('°C');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="temp" id="holder_1443531366" style="text-align:center; display:inline-block;"><span class="degrees">86.1</span>
<span class="degType" style="padding-left:3px;">°F</span>
</span>
<br/><br/>
<span class="temp" id="holder_1443531366" style="text-align:center; display:inline-block;"><span class="degrees">212</span>
<span class="degType" style="padding-left:3px;">°F</span>
</span>
<br/><br/>
<a class="toC" href="#">to Celcius<a/>
Here's a way to toggle back and forth
$('a').click(function () {
$('span.temp').each(function () {
if ($(this).find('span:last').text() == '°F') {
$(this).find('span:last').text('°C');
$(this).find('span:first').text(parseFloat((($(this).find('span:first').text() - 32) * 5) / 9).toFixed(2))
} else {
$(this).find('span:last').text('°F');
$(this).find('span:first').text(parseFloat((($(this).find('span:first').text() * 9) / 5) + 32).toFixed(2))
}
})
$(this).text($(this).text() == 'switch to Fahrenheit' ? 'switch to Celsius' : 'switch to Fahrenheit')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="temp" id="holder_1443531366" style="text-align:center; display:inline-block;">
<span style>86.1</span>
<span style="padding-left:3px;">°F</span>
</span>
<span class="temp" id="holder_1443531367" style="text-align:center; display:inline-block;">
<span style>212</span>
<span style="padding-left:3px;">°F</span>
</span>
switch to Celsius
Try using .find() to filter first span , .html(function(index, html){}) to convert Fahrenheit to Celsius , select next span to change F to C
$(".temp").each(function(index, el) {
$(this).find("span:first").html(function(_, temp) {
return ((temp - 32) * 5/9).toFixed(2)
}).next("span").html(function(_, sym) {
return sym.slice(0,1) + "C"
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<span class="temp" id="holder_1443531366" style= "text-align:center;display:inline-block;"><span style>86.1</span><span style="padding-left:3px;">°F</span></span>
<span class="temp" id="holder_1443531376" style= "text-align:center;display:inline-block;"><span style>85.38</span><span style="padding-left:3px;">°F</span></span>
I've made a working example and tested it to be working
http://jsfiddle.net/a2dax16t/
I've created a sample set of spans as you did, but added a button to trigger the function:
<span class="temp" id="holder_1443531366" style="text-align:center;display:inline-block;">86.1</span>
<br/>
<span class="temp" id="holder_1443531366" style="text-align:center;display:inline-block;">99</span>
<br/>
<span class="temp" id="holder_1443531366" style="text-align:center;display:inline-block;">102</span>
</span>
<br/>
<button id="btnCelsius">Convert</button>
and here is my function:
$(function () {
$("#btnCelsius").click(function () {
$(".temp").each(function () {
var newValue = $(this).html();
$(this).html(toCelsius(newValue));
});
});
});
function toCelsius(f) {
return (5 / 9) * (f - 32);
}
as you can see, I've created a function to convert to celsius, and used it inside the each() function, and tested it and it's working.
please give it a try and let me know if this is what you want or that you need any extra modifications.
Related
I am currently trying to loop through multiple input boxes using loops but I don't know how to go about doing it.
My JS code:
function tagger() {
var t;
for (t = 0; t < 5; t++) {
document.getElementsByClassName("pl")[0].getElementsByTagName("input")
}
};
return tagger();
HTML:
<h1 class="pizza">Pineapple</h1>
<body class="maco">
<div class="keys">
<span class="press" onclick="car()"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span class="type" id="heyu"><input class="entry" placeholder="Password"></span>
</div>
</body>
</html>
Thanks in advance for any help rendered!
You must to add the t variable as index of (getElementsByTagName)
document.getElementsByClassName("pl")[0].getElementsByTagName("input")[t];
or you can use forEach Method is the best way for looping trough arrays
function tragger () {
var _Element = Array.from(document.querySelector("pl input"));
_Element.forEach(function (ele) {
//do some code for each input
ele.value = 'etc';
});
}
tragger();
I know this question seems like a repeat, but I've waded through many similar questions and have had no success.
I am working with a financial reporter and want to make negative balances red and positive balances green.
Here is my current jQuery. When I debug in the browser, the entire function gets skipped. Yet for some reason, my classes are ALL getting changed to text-dang.
$('.balance').each(function (i) {
var content = $(this).text().replace('$', '');
var balance = parseInt(content, 10);
if (balance <= 0)
{
$('.balance').removeClass("text-succ").addClass("text-dang");
}
else {
$('.balance').removeClass("text-dang").addClass("text-succ");
}
});
I have also tried it without the wrapping function - $('.balance').each(function (i) { - but then only the FIRST element with class .balance was selected.
Here is my HTML. (Note that I am using Razor, and iterating through multiple accounts which will all contain this h2. The balances were coming in just fine until I used the wrapping function.)
<h2>
<strong>#account.Name</strong>
<i class="fa fa-angle-right"></i>
Balance: <span class="balance text-succ">$ #account.Balance</span>
</h2>
I'm pretty new to Javascript and StackOverflow so please let me know if you need more information. Any help is appreciated!
The problem is that you're updating all elements on each iteration. You need to use this to select the current element.
$('.balance').each(function(i) {
var $this = $(this);
var content = $this.text().replace('$', '');
var balance = parseInt(content, 10);
if (balance <= 0) {
$this.removeClass("text-succ").addClass("text-dang");
} else {
$this.removeClass("text-dang").addClass("text-succ");
}
});
.text-succ {
color: green;
}
.text-dang {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2><strong>Account1</strong> <i class="fa fa-angle-right"></i> Balance: <span class="balance text-succ">-4</span></h2>
<h2><strong>Account2</strong> <i class="fa fa-angle-right"></i> Balance: <span class="balance">-2</span></h2>
<h2><strong>Account3</strong> <i class="fa fa-angle-right"></i> Balance: <span class="balance">0</span></h2>
<h2><strong>Account4</strong> <i class="fa fa-angle-right"></i> Balance: <span class="balance">2</span></h2>
<h2><strong>Account5</strong> <i class="fa fa-angle-right"></i> Balance: <span class="balance">4</span></h2>
You need to apply and remove class to the referred element, in this case $(this) instead of $('.balance').
Check this fiddle
$('.balance').each(function(){
var balance = parseInt($(this).text().replace('$',''), 10);
$(this).removeClass("text-dang").addClass("text-succ");
if (balance <= 0)
$(this).removeClass("text-succ").addClass("text-dang");
});
remember you are looping through all elements... when $('.balance').each loops call the anonymous function and uses $(this) to refer to the $(".balance") element that is object of the iteration...
$('.balance').each(function (i) {
var content = $(this).text().replace('$', '');
var balance = parseInt(content, 10);
if (balance <= 0)
{
$(this).removeClass("text-succ").addClass("text-dang");
}
else {
$(this).removeClass("text-dang").addClass("text-succ");
}});
There is a toogleClass that could take two parameters, one the string for the class and the second one a logic test... so you could do something like:
$('.balance').each(function (i) {
var content = $(this).text().replace('$', '');
var balance = parseInt(content, 10);
//to be on the safe side:
$(this).removeClass();// or $(this).removeClass("text-dang text-succ");
$(this).toggleClass("text-dang", balance <= 0);
$(this).toggleClass("text-succ", balance > 0);
});
Well is just an idea...
I'm writing script which should find onclick attributes on any ancestor.
For example when I click on span.tabIdent I want get anchor onclick (I trigger it later)
HTML:
<a class="t3 lin tab-B" rel="#categoriesLinux" rev="lin" onclick="changeTab()">
<span class="tabLeft" style=""></span>
<span class="tabCenter" style="">
<span class="tabIdent" style=""></span>
</span>
<span class="tabRight"></span>
</a>
JS:
var foo,
foo2,
przodek,
parentsCount = jQuery(that).parents().length,
przodek = jQuery(that); //it's ok here
for(var ii=0; ii<parentsCount; ii++){
przodek = jQuery(przodek).parent();
foo = jQuery(przodek).prop('nodeName'),
foo2 = jQuery(foo).attr('onlick');
console.log(foo+' : '+foo2);
}
It return everywhere 'undefined'.
What is wrong with this ?
You make a spelling error: onlick is not onclick
You could simply do this...
$('.tabIndent').on('click', function() {
var anchor = $(this).closest('a');
console.log(anchor.prop('nodeName') + ' : ' + anchor.prop('onclick'));
});
There's a page with some HTML as follows:
<dd id="fc-gtag-VARIABLENAMEONE" class="fc-content-panel fc-friend">
Then further down the page, the code will repeat with, for example:
<dd id="fc-gtag-VARIABLENAMETWO" class="fc-content-panel fc-friend">
How do I access these elements using an external script?
I can't seem to use document.getElementByID correctly in this instance. Basically, I want to search the whole page using oIE (InternetExplorer.Application Object) created with VBScript and pull through every line (specifically VARIABLENAME(one/two/etc)) that looks like the above two into an array.
I've researched the Javascript and through trial and error haven't gotten anywhere with this specific page, mainly because there's no tag name, and the tag ID always changes at the end. Can someone help? :)
EDIT: I've attempted to use the Javascript provided as an answer to get results, however nothing seems to happen when applied to my page. I think the tag is ALSO in a tag so it's getting complicated - here's a major part of the code from the webpage I will be scanning.
<dd id="fc-gtag-INDIAN701" class="fc-content-panel fc-friend">
<div class="fc-pic">
<img src="http://image.xboxlive.com/global/t.58570942/tile/0/20400" alt="INDIAN701"/>
</div>
<div class="fc-stats">
<div class="fc-gtag">
<a class="fc-gtag-link" href='/en-US/MyXbox/Profile?gamertag=INDIAN701'>INDIAN701</a>
<div class="fc-gscore-icon">3690</div>
</div>
<div class="fc-presence-text">Last seen 9 hours ago playing Halo 3</div>
</div>
<div class="fc-actions">
<div class="fc-icon-actions">
<div class="fc-block">
<span class="fc-buttonlabel">Block User</span>
</div>
</div>
<div class="fc-text-actions">
<div class="fc-action"> </div>
<span class="fc-action">
View Profile
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Compare Games
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Message
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Friend Request
</span>
</div>
</div>
</dd>
This then REPEATS, with a different username (the above username is INDIAN701).
I tried the following but clicking the button doesn't yield any results:
<script language="vbscript">
Sub window_onLoad
Set oIE = CreateObject("InternetExplorer.Application")
oIE.visible = True
oIE.navigate "http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=12"
End Sub
</script>
<script type="text/javascript">
var getem = function () {
var nodes = oIE.document.getElementsByTagName('dd'),
a = [];
for (i in nodes) {
(nodes[i].id) && (nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
}
</script>
<body>
<input type="BUTTON" value="Try" onClick="getem()">
</body>
Basically I'm trying to get a list of usernames from the recent players list (I was hoping I wouldn't have to explain this though :) ).
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
alert(a[0]);
};
please try it by clicking here!
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
};
try it out on jsbin
<body>
<script type="text/javascript">
window.onload = function () {
var outputSpan = document.getElementById('outputSpan'),
iFrame = frames['subjectIFrame'];
iFrame.document.location.href = 'http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=1';
(function () {
var nodes = iFrame.document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
for (var j in a) if (a.hasOwnProperty(j)) {
outputSpan.innerHTML += (a[j] + '<br />');
}
})();
};
</script>
<span id="outputSpan"></span>
<iframe id="subjectIFrame" frameborder="0" height="100" width="100" />
</body>
What does "I can't seem to use document.getElementsByID correctly in this instance" mean? Are you referring to the fact that you are misspelling getElementByID?
So...something like this (jQuery)?
var els = [];
$('.fc-content-panel.fc-friend').each(function() {
els.push(this));
});
Now you have an array of all the elements that have both of those classes.
Say i have the following html:
<span class="fruit">Apple</span>
<span class="fruit">banana</span>
<span class="fruit">Apple</span>
<span class="fruit">Apple</span>
<span class="fruit">orange</span>
I tried different methods but it didn't work, I want a jQuery code to remove all (.fruit) spans with same content but keep one (the first if possible), so i will end up with the following:
<span class="fruit">Apple</span>
<span class="fruit">banana</span>
<span class="fruit">orange</span>
Thank you
$("span.fruit:contains(Apple):not(:first)").remove();
$('span.fruit').each(function(){
return $('span.fruit:contains('+$(this).text()+'):not(:first)').remove();
})
var temp = array[];
$(".fruit").each(function(i) {
var html = $($this).html();
if($.inArray(html, temp)) {
$($this).remove();
}
else {
temp.push(html);
}
});
temp = $('span:first').clone(true);
//remove all the span
$().html();
$().append(temp);