I can't find why I'm receiving a NaN for printing a number out with javascript.
The following code I use is repeated elsewhere on the website and works fine.
The URL in question is: http://all-american-gold10.mybigcommerce.com/us-silver-eagles/
My code is as follows:
function setCheckPrice() {
$('.NormalPrice').each(function(key, val) {
var price = $(val).html().replace('$', '').replace(',', '');
var newPrice = parseInt(price) * .03;
var setPrice = Math.floor(price - newPrice);
var credit = '<small style="font-size: 20px !important;"> - credit card price</small>';
var check = '<p><em class="new-price">$' + setPrice +'<small style="font-size: 20px !important;"> - check price</small></em></p>';
$(val).append(credit);
$(val).prepend(check);
})
};
setCheckPrice();
My code takes a number found by a specific class name, does some math and spits in back out with some extra html to go along with it. I've tried to switch the ways I've outputted the code with append, prepend, before & after, but none seem to work? Any reason why this is acting so strange?
The price variable has additional html in it. You should consider having separate elements with a class that contains just the value that you need, and nothing else. As a quick fix, this change:
var price = $(val).val().replace('$', '').replace(',', '').replace(" ","");
get's me a value of 490 for price on that page, which is what you're looking for.
Related
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.
looking to have the user click the button and have the fortune be selecting randomly and shown on the screen with random numbers from 1-100 underneath them. but i can't seem to get everything to display. :(
<script type = "text/javascript">
var quotes = new Array(16) // Add your quotes below
quotes[0]="Your talents will be recognized and suitably rewarded.";
quotes[1]="He who hurries cannot walk with dignity.";
quotes[2]="Your success in life must be earned with earnest efforts.";
quotes[3]="You love peace.";
quotes[4]="A friend asks only for your time and not your money.";
quotes[5]="You will soon inherit a piece of land.";
quotes[6]="Your luck is about to change.";
quotes[7]="Things will soon go your way.";
quotes[8]="He who stands on toilet is high on pot.";
quotes[8]="Everybody is ignorant, only on different subjects.";
quotes[9]="Fortune favors the brave.";
quotes[10]="There is nothing permanent except change.";
quotes[11]="You haven't failed until you give up.";
quotes[12]="Your ability to juggle many tasks will take you far.";
quotes[13]="Broke is only temporary; poor is a state of mind.";
quotes[14]="Begin nothing until you have considered how it is finished.";
quotes[15]="A huge fortune at home is not as good as money in use.";
function showFortune() {
var space = (' ') // Spacer for between numbers
var rand_inta = Math.floor(Math.random()*100); // Get first number
var rand_intb = Math.floor(Math.random()*100); // Get second number
var rand_intc = Math.floor(Math.random()*100); // Get third number
var rand_intd = Math.floor(Math.random()*100); // Get fourth number
var rand_inte = Math.floor(Math.random()*100); // Get fifth number
var rand_int = Math.floor(Math.random()*16); // Get a number for picking the quote
document.getElementById(fortuneArea).innerHTML=(quotes[rand_int]); // Put the quote in the box
}
</script>
<form action="">
<input type="button" value="Show my fortune!" onclick= "showFortune();" />
</form>
<div id="fortuneArea"></div>
document.getElementById('fortuneArea').innerHTML=(quotes[rand_int]);
Just add single quotes to id name....
What i'm trying to do is taking the price of every input checked, making a sum out of it.
Here's my code
function totalSum(e) {
e.preventDefault();
var unit = $("input:checked").parent("dt").siblings("dd").find("span");
total = 0;
$.each(unit, function(index, obj){
total += parseInt($(obj).text(), 10);
});
$("#totalPrice").html('<span class="count">€ ' + total + '</span> €');
}
Every unit is found inside its span. Total is set to 0. I try to call a parseInt on each checked object, then add the total inside a span. In HTML, price is stated like that:
<dd><span class="costo">€199</span></dd>
So as you see there is the Euro mark. I am afraid it could not be parsed, is this it? Because nothing change! How should I write it?
Thanks in advance
Ok I feel so ashamed but I cannot get it to work. I decided to put the code at its minimum, so I tried that way
<body>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div id="total"></div>
<script type="text/javascript" src="js/jquery-1.9.0.min.js" /></script>
<script>
$(document).ready(function(){
function sum() {
var prices = $("div.bla").find(".count");
total= 0;
$.each(prices, function(index, obj){
total += parseFloat($(obj).text());
});
$("#total").html('<span class="count">'+total +'</span> €');
};
});
This should work, yet nothing appear. Could someone be so kind to tell me what's going wrong?!
You can just replace any non-numeric characters:
total += parseInt($(obj).text().replace(/[^\d.-]/, ''), 10);
Also, you can do unit.each() instead of $.each(unit, but that has no effect on what you're trying to do.
You can simply remove the unit from the text :
var text = $(obj).text().replace(/[€\$]/,''); // add other units if needed
total += parseInt(text, 10); // are you sure you don't prefer parseFloat ?
Or, if you want to only keep digits and + and -, do
var text = $(obj).text().replace(/[^\d\-\+]/g, '');
Change your parseInt to skip the first character.
total += parseInt($(obj).text().substring(1),10);
After a couple of days trying and reading the best way to do it, I believe this could be an elegant solution of what I was trying to achieve :)
$("input").on("click", function() {
var j = $("input:checked");
t = 0;
$(j).each(function() {
t += parseInt(this.value, 10);
});
$("#total").html("<span>€ " + t + "</span>");
});
Markup::
<td class="info2 gensmall">
<span class="new1">In total there is <strong>1</strong> user online :: 1 Registered, 0 Hidden and 0 Guests </span>
<span class="new2">We have <strong>4</strong> registered users</span>
<span class="new3">The newest registered user is <strong>cldtomhil</strong></span>
<span class="new4">Our users have posted a total of <strong>12</strong> messages</span>
</td>
Ok guys trying to learn the jQuery .split
$(document).ready(function(){
var a = $('td .info2 .new1');
var b = $('td .info2 .new2');
var c = $('td .info2 .new3');
var d = $('td .info2 .new4');
var w = a.split("<strong>");
var x = b.split("<strong>");
var y = c.split("<strong>");
var z = d.split("<strong>");
$('.new1').html('<span>"w"</span> Users Online');
$('.new2').html('<span>"x"</span> Total Users');
$('.new3').html('<span>"y"</span> Newest Member');
$('.new4').html('<span>"z"</span> Total Messages')
});
Ok I know I am doing this wrong just by looking at it. Though I just can't figure out how to use the split feature, I am trying to gain the information inside the <strong> tags. Then once I have it I want to change the innerHTML basically with the new data like I posted with the .html
Yes I know it's a lot of variables but hey what can you do, I'm not a very good coder yet, and still learning some things so.
Here is how you gain the value:
$('td.info2 .new1 strong').text(); // returns "1"
$('td.info2 .new3 strong').text(); // returns "cldtomhil", not "cldtomhil"
Etc. Having said that, String.split is a JavaScript function that splits strings given a separator. What you were trying to do was to grab the contents of an HTML element. There is no need to use string functions to do this. Use DOM functions (or jQuery) to manipulate the DOM.
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product