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.
Related
I have this html:
<span class="price-amount amount"><span class="price-currencySymbol">£</span>49.99</span>
I want to extract just the value of '49.99' without the html and currency symbol.
I have tried this:
function() {
var element = document.querySelector('.price-amount');
var price = element.innerHTML.replace('£', '');
return price;
}
But the result is this:
<span class="price-currencySymbol">£</span>49.99
Rather than: 49.99
Try this
var price = element.innerHTML.match(/\d+\.\d+/)[0];
where
.match searches the pattern of price using regex.
[0] returns the first match, and in your case it would be the only match.
If you want to delete what's in the '.price-currencySymbol' span in every case, you juste have to empty its html:
document.querySelector(".price-amount").innerHTML = "";
By using selector logic and accessing the proper text node you don't even need to use regexp.
var price = document.querySelector(".price-amount")
.childNodes[1].textContent;
console.log(`Extracted price: ${price}`);
<span class="price-amount amount"><span class="price-currencySymbol">£</span>49.99</span>
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.
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.
I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks,
Traci
You will want to use the value property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent (or innerText to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.
Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/
In this line, you'll want to set the innerHTML of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p> to be <p>$x.xx</p>.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,
imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.
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