Convert text to integer and if higher than 50 alert - javascript

On our current website that is hosted offsite via another company it is all done with .NET, I simply have access to HTML, JS, and CSS files to edit. A lot of data is output on the page via tokens. On our web page we have a weight token, it grabs the items weight and outputs it between a span tag. So if you're viewing the source it'll show the following:
<span id="order_summary_weight">78.000000 lbs</span>
The token by default outputs the lbs. What I need to do is have javascript grab the 78.000000, convert it to an integer I'm assuming and if that integer, in this case 78.000000 is greater than 50.000000 I'd like it append a line after the 78.000000 lbs to say "Your weight total is over 50 lbs, we will contact you directly with a shipping charge." Understand some weight totals may be as small as 0.010000
I'm coming to you fine folks here because I am at a complete lost where to start in this endeavor.

Something like this ? :
html :
<div class="wrap">
<span class="price" id="order_summary_weight">78.000000 lbs</span>
</div>
<hr>
<div class="wrap">
<span class="price" id="order_summary">50.000000 lbs</span>
</div>
JS :
$('.wrap').each(function(){
var price = $(this).find('.price').text();
price = price.replace(' lbs', '');
price = parseInt(price);
if(price > 50){
$(this).append('<div class="alert">Your weight total is over 50 lbs, we will contact you directly with a shipping charge.</div>');
}
});
DEMO : http://jsfiddle.net/w3qg4/1/

function getWeight()
{
var x=document.getElementById("order_summary_weight");
if(x > 50){
alert("Your weight total is over 50 lbs, we will contact you directly with a shipping charge. Understand some weight totals may be as small as 0.010000");
}
}

Related

Ruby script to calculate discount using Shopify Scripts

I am using a script to calculate an addtional 5% off when the cart total is greater than $1000, but the variant price is already discounted by 25% and has a was/now pricing setup that is $29.95 was $39.95.
The problem is - i need for the script to discount the orginal item value of $39.95, not the discounted rate which is the new retail price.
Here is the script - i have tried to add 25% back to the line item price without success and there is no line item method that Shopify provides to use the orginal cart line item price in the dev docs - https://help.shopify.com/en/manual/checkout-settings/script-editor/shopify-scripts#line-item-methods
# Tiered Discounts by Spend Threshold 5% off when you spend $1000 or more
min_discount_order_amount_extra = Money.new(cents:100) * 1000 #number of dollars needed in cart to get the discount
DISCOUNT_PERCENT = 25
# calculate the discount to be applied
percent = Decimal.new(DISCOUNT_PERCENT/100) + 1
total = Input.cart.subtotal_price_was * percent
discount = if total > min_discount_order_amount_extra
0.05 #discount percentage in decimal form
else
0
end
message = "Another 5% saved"
# 30% off products excluding commercial items
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next if product.gift_card?
next if line_item.variant.product.tags.any?{|x| ['commercial'].include?(x)};
line_item.change_line_price(line_item.line_price * (1-discount), message: message) unless discount == 0
end
Output.cart = Input.cart

Displaying 2 custom Data attribute items within a div. Ex: Currency & Amount

I have an E-Commerce website built on HTML, JavaScript & PHP.
On product details page user can add product to cart thus I'm displaying total amount of cart value.
I want to display decimal number always (10,2) format.
Currently my code works with minimal thing. On clicking "Add to cart" if product price is 12.00 the Counter div displays 12 only.
<span>
<a href="cart.php" class="text-white">
<i class="fa fa-shopping-cart p1" data-count="10" data-currency="€" id="total"></i>
</a>
</span>
.p1[data-count]:after{
position:absolute;
right:1%;
top:1%;
content: attr(data-count);
font-size:10px;
padding:.2em;
line-height:1em;
color: white;
background:#21468b;
text-align:center;
width: 100%;
font-weight:normal;
}
<script>
var theTotal = '0';
var ProductSellingPrice = '12.00'
$('#insert').click(function(){
theTotal = Number(theTotal) + Number(ProductSellingPrice);
$('#total').attr('data-count', theTotal);
});
</script>
So on clicking insert, the existing TheTotal & current product Price gets added. If there are no products on cart then p1 doesn't display any value, thus want to display zero always if empty/zero. If product price is 12.00 then shows 12 only. If product price is 12.50 then 12.50 is displayed.
I want it to display decimal always & also currency symbol using data attribute.
Displaying decimal problem is solved by #Simone, i m not able to find answer for displaying currency before value using data attribute.
If you want 12.00 and not 12 you have to use Number.prototype.toFixed()
So you have to convert all the single product total (quantity * price is the single total ) into Float number and when you do the total sum, take the number and do this:
Number.parseFloat(total).toFixed(2); // two decimal
Example:
var quantity = 10;
var price = 11;
var tot = parseFloat(quantity * price).toFixed(2);
console.log(tot); // "110.00"

How should i display number in HTML for later calculation in javascript

I am trying to figure out how to display number a right and efficient way for later calculation in HTML. This is what i can think of right now but doesn't seems right.
<p class = "price"> <span class ="sign">$</span> 10 </p>
Later implementation includes
$("p.price") * (the desire currency rate being called)
It then updates the whole page with the p.price
Consider using data attributes:
<p class="price" data-usd-price="10"> any markup you want </p>
You can then format it however you like and access the raw value later with:
$("p.price").data("usd-price")
Here a bit more complicated example:
<p class="price" data-usd-price="10">foo<span class="converted"></span></p>
<p class="price" data-usd-price="30">bar<span class="converted"></span></p>
<p class="price" data-usd-price="49.99">buzz<span class="converted"></span></p>
<p class="price" data-usd-price="99.99"><span class="converted"></span></p>
$('p.price').each(function () {
$(this)
.children('span.converted')
.html(
$(this).data('usd-price') * 22
)
})
The selector $("p.price") will give you an array of all paragraph elements with the class price. So your first issue is that you need to be aware of that, and your current multiplication code is not.
Second, you're trying to multiply the elements rather than the value of the one element.
Third, the value will be a string and you need a number.
I'd try something like:
<p class="price"><span>$</span><span class="amount">10</span>
Then your JS could look like this (minus smart error checking and optimization and such)
var amount = parseFloat($("span.amount:first").text(), 10);
$("span.amount:first").text(amount * exchangeRate);
Try to loop through paragraph children and check, if nodeName of the children is text then parse it's wholeText
var pContent = $('.price')[0].childNodes,
elem, num;
$.each(pContent, function (i, e) {
elem = $(e)[0];
if (elem && elem.nodeName == "#text") {
num = parseInt(elem.wholeText);
}
})
console.log(num)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<p class = "price"> <span class ="sign">$</span> 10</p>
when the page load the span is left empty but i want it to be shown (GBP as the base)
Simply change the spans text on window load instead of onchange event
var selectedIndex = select.selectedIndex;
$('.sign').text(prefix[selectedIndex ]);
$('.converted').text(currency[selectedIndex ] * $(price).data('price'));
Also i have some notes, if you have just one element you don't need to implement each function , and you don't need to make loop on each change as selectedIndex will filter the option which has selected attribute. http://jsfiddle.net/whoq9zd0/2/

If greater than shipping weight check

I am trying to get new website off the ground through bigcommerce and found out they don't have anything for freight shipping. I know enough to identify my problem and the code that needs changed within the template file but not create code to do what I want. Currently shipping is calculated at checkout and displays "Calculated at checkout" The block of code displaying the shipping is
<div class="DetailRow" style="display: %%GLOBAL_HideShipping%%">
<div class="Label">%%LNG_Shipping%%:</div>
<div class="Value">
%%GLOBAL_ShippingPrice%%
</div>
</div>
I need the line %%GLOBAL_ShippingPrice%% which makes "Calculated at checkout" appear only on items under 150lbs and for items greater than 150lbs the message "Contact us for a shipping quote". Weight is currently generated in the listing by the a block of code in the same file reading.
<div class="DetailRow" style="display: %%GLOBAL_HideWeight%%">
<div class="Label">%%LNG_Weight%%:</div>
<div class="Value">
<span class="VariationProductWeight">
%%GLOBAL_ProductWeight%%
</span>
</div>
</div>
It seems %%GLOBAL_ProductWeight%% is what probides the weight displayed but it reads "xyz LBS" and since it adds LBS to the number I'm not sure how to write code to check the return as greater or less than 150 or how to get it to then display the correct message. If any additional information is needed to create a code to do this let me know and I will provide it.
You can use the "replace" js function to remove the "LBS" string from your text.
(function getCorrectTextBasedOnWeight() {
var weightSpanElements = document.getElementsByClassName('VariationProductWeight');
var answerMessageSpan = document.getElementById('answerMessage');
for (var i = 0; i < weightSpanElements.length; ++i) {
var item = weightSpanElements[i];
var weightValue = item.innerHTML.replace("LBS", "");
if (weightValue <= 150) {
answerMessageSpan.innerHTML = "Calculated at checkout";
} else {
answerMessageSpan.innerHTML = "Contact us for a shipping quote";
}
}
})();
You can use this sample in JSFiddle: http://jsfiddle.net/amontellano/YdV4S/
Simply change the value inside of the span of the HTML section and you will see how the answerMessage display the correct text based on weight value.

split a big HTML page to pages on client side

I have a huge HTML page which is mainly a form which is mostly like this:
<FIELDSET id= '1'>
<TABLE>
<TR> </TR>
</FIELDSET>
</TABLE>
.
.
.
<FIELDSET id= 'n'>
<TABLE>
<TR> </TR>
</TABLE>
The number of fieldsets are generated by dynamically on the server.
Question: On the client side I want to do a pagination for this huge page, so that only say,3 fieldset appear per page on the client.
I don't want to change the way page is loading or form is being submitted currently.
Well just a little tips you may use
$('fieldset')
document.querySelectorAll('fieldset')
will return you fields
in order to get show only i .. i+3 fieldsets you can use
var i = 3
$('fieldset').hide().each(function ( index, el) {
if (index >= i && index < i+3) $(el).show()
})
var fieldsets = [].slice(document.querySelectorAll('fieldset'))
for (var index in fieldsets) {
var display = index < i && index >= i+3 ? 'none' : ''
fieldsets[index].style.display = display
}
Pagination won't really help you in any way other than visual if done on the client side (no speed increases, load reductions, etc), but if that's what you want you can do it with DOM manipulation. Something like the following might work for you:
var i=0,sets=document.getElementsByTagName('fieldset'),len=sets.length;
for(;i<len;i+=3) {
// wrap sets[i] through sets[i+2], as long as they exist, in a div
// if i !== 0, hide or minimize the div
}
// add controls to unhide/unminimize each div

Categories