Price format, change size after decimal - javascript

I use this code to format price:
$.each($('.price-lbl-cust'), function() {
var price = $(this).html();
$(this).html(price.replace(/(\D*)(\d*\,)(\d*)/,
'<span style="font-size:16px;font-weight:600;">$1</span><span style="font-size: 1.675rem;line-height: 1.5rem;font-weight:600;">$2</span><span style="font-size: .92222em;font-weight:600;">$3</span>'
));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price-lbl-cust">144,40</div>
this give me output:
is correct.
But the issue is when price is example:
2,948,11
then give me output:
only first number 2 is big, and second 948 and third 11 is small.
How to change and add when price have 2 decimal then make small price only after last decimal ?

Try this :
/(\d*\,)(\d*\,)*(\d+)/ will make sure to select everything before the last comma.
$.each($('.price-lbl-cust'), function() {
var price = $(this).html();
$(this).html(price.replace(/(\d*\,)(\d*\,)*(\d+)/,
'<span style="font-size: 1.675rem;line-height: 1.5rem;font-weight:600;">$1</span><span style="font-size: 1.675rem;line-height: 1.5rem;font-weight:600;">$2</span><span style="font-size: .92222em;font-weight:600;">$3</span>'
));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price-lbl-cust">2,948,11</div>

Related

Creating step numbers dynamically in jquery

I hate manually typing steps numbers. So I was trying to write a small function to find some text and replace it with generated step numbers.
And I can't use the ol/li tags because I have multiple groups on the page. So I need to add an "a", "b", etc after the number.
My HTML:
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
This is my jquery (but it doesn't replace the ---- to a step number).
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
$(this).find(":contains('----')").each(function(){
$(this).text("("+counter+val+") ");
counter++;
});
});
});
So eventually, I want the webpage to finish like this:
(1a) My first step
(2a) This is another
(3a) And another
(1b) second group
(2b) second group 2
For each of the groupings, get the inner html and split it by newline
If it starts with '----', replace it with an incrementing line number, and append the v value.
Put the html back into the grouping.
$('.grouping').each(function(index, grouping){
var lines = grouping.innerHTML.trim().split("\n");
var lineNumber = 0;
var v = grouping.getAttribute('v');
lines.forEach(function(line, index){
if (line.startsWith('----')) {
lines[index] = '('+ (++lineNumber) + v +') '+ line.slice(4);
}
});
grouping.innerHTML = lines.join('\n');
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
I should not have a line number.
----And another
</span>
<br/>
<span class="grouping" v="b">
I also should not have a line number.
----second group
----second group 2
</span>
You can use split to split the text at '----' and concat with the values (added brs for lisibility so I used html instead of text):
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var arr = $(this).html().split('----');
if(arr.length > 1){
var str = arr[0], i, l = arr.length;
for(i = 1; i < l; i++){
str += '(' + i + val + ') ' + arr[i];
}
$(this).html(str);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step<br>
----This is another<br>
----And another<br>
</span>
<br/>
<span class="grouping" v="b">
----second group<br>
----second group 2<br>
</span>
.find() will not work. You should get text of the element and split() it and then change it using map() and replace() and reset text()
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
let lines = $(this).text().split('\n');
lines = lines.map(ln => {
if(ln.includes('----')){
ln = ln.replace('----',`(${counter}${val})`)
counter++;
}
return ln;
})
lines = lines.filter(ln => ln !== '');
$(this).text(lines.join('\n'));
});
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
First, I suggest wraping those groups into some kind of tag. for example, span:
<span class="grouping" v="a">
<span class="grouping-item">My first step</span>
</span>
And so on, it will be easier and faster to target those elements.
Then create one function to search through those new tags
$(function(){
// This will create those numbers
function createNumbers(el) {
const mainGroup = el.attr("v");
const children = el.children(".grouping-item");
let i = 1;
children.each(function(){
const currentText = $(this).text();
$(this).text( '('+i+mainGroup+')' + currentText );
i++;
});
}
$(".grouping").each(function(){
createNumbers($(this));
});
});

Simple Math with JS

Hello I need a quick hand, I have this div below
<div class="price">$1500</div>
I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.
<span class="payment">Pay as low as $"result here" </span>
I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.
First get text of div var text = $('.price').text(); // "$1500"
Then parse it as integer var price = text.replace(/[^\d]/, ''); // "$1500" -> 1500
Finally place text to where it belongs: $('.payment').text('Pay as low as $'+(price / 2 / 6));
$(document).ready(function () {
var text = $('.price').text();
var price = text.replace(/[^\d]/, '');
$('.payment span').text(price / 12);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $<span></span> </span>
Here, this one is pure javascript, try not to overcomplicate things
<html>
<body>
<div id="num">1500$</div>
<div id="num2"></div>
<script>
var number = document.getElementById("num").innerHTML.replace("$", "");
number = number / (2 * 6);
document.getElementById("num2").innerHTML = "Pay as low as " + number + " here";
</script>
</body>
</html>
You can achieve this as below mentioned.
$(document).ready(function(){
var price = $(".price").text(),
price = price.replace('$', '');
finalPrice = (price/2).toFixed(2);
$(".final-price").text(finalPrice/6);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<br> <br>
<div class="payment">Pay as low as $<span class="final-price"></span> </div>
get the text() of the element.
replace the $ sign
And divide by (2*6)
Apply with some Math.abs function its will calculate the result
Then apply the span and append into your body
var a = Math.abs(parseInt($('.price').text().replace('$',''))/(2*6))
$('body').append('<span class="payment">Pay as low as $'+a+' </span>')
.payment{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
Try this
var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
Demo
var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $"result here" </span>
What you should do:
Get the .price div's text.
convert it to an int.
Now you should divide it with (value/2)/6
Put the value in the desired target element.
var price = +$('.price').text().slice(1);
var pay = (price/2)/6
$('p').text("Pay as low as $"+pay);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<p></p>
hope it help.
/*define a function to Deleting all characters other than numbers. in element*/
function checkIsInteger(sTr){
var newstr = "";
if(typeof sTr !== "undefine" && sTr!=""){
var indexInt = ['0','1','2','3','4','5','6','7','8','9'];
for(var i=0;i<sTr.length;i++){
var cek = sTr.substr(i,1)
if(indexInt.indexOf(cek)>=0){
newstr += sTr.substr(i,1);
}
}
}
return newstr;
}
$("#res").html((parseInt(checkIsInteger($("#price").html()))/2)/6);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="price" id="price">$1500</div>
<label class="payment" id="pym">Pay as low as $<span id="res">result</span> here </label>

Sum numbers returns NaN

I'm trying to do a sum of numbers inside div's, so, I did:
$(document).ready(function() {
var numbers, sumNumbers;
$(".item").each(function() {
numbers = $(this).children().text();
numbers = +numbers;
sumNumbers += numbers;
});
console.log(sumNumbers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<span class="itemNum">0</span>
</div>
<div class="item">
<span class="itemNum">2</span>
</div>
<div class="item">
<span class="itemNum">1</span>
</div>
But, same converting the numbers from text to number with +numbers is returned NaN, why? I've already tried with Number(numbers) too but the result is the same.
You didn't initialize sumNumbers, so you get undefined + a number = NaN
var numbers, sumNumbers = 0;
Try this
var numbers=0, sumNumbers=0; //initilize numbers & sumNumbers;
$(".item").each(function () {
numbers = $(this).children().text() * 1; // *1 convert string to number
sumNumbers += numbers;
});
console.log(sumNumbers);

How would I create a Drag and Drop feature with Image Arrays?

I am having a hard time figuring out how to create a drag and drop feature in my app that will accept a draggable item and decide whether it is the correct answer and if it is correct it will display a message saying success!
My app displays two images both images are portions of a pizza pie and then it will display 8 draggable numbers that you have to choose from and drag them into a droppable box which will check if its correct. So i start with ...
PizzaImageOne[1]="http://s23.postimg.org/6yojml8vb/Pizza_One.png"
PizzaImageOne[2]="http://s13.postimg.org/5d8zxnb2b/pizzatwo.png"
this happens 8 times so each number of the array represents how many slices it holds
then i call var whichImage = Math.round(Math.random()*(p-1)); i store a random # into the variable whichImage which holds the number of pizza slices because each array # correlates with the pizza slices image which i will use to generate random pizzas by doing this
document.write('<img src="'+theImages[whichImage]+'">');
I do that all over again with a new array
PizzaImageTwo[1]="http://s23.postimg.org/6yojml8vb/Pizza_One.png"
PizzaImageTwo[2]="http://s13.postimg.org/5d8zxnb2b/pizzatwo.png"
same exact thing but with new variables so the random call can be different than the first one
var whichImage2 = Math.round(Math.random()*(p-1))
then i have
<script>
$(function() {
$( "#draggable1" ).draggable();
});
</script>
I do that 8 times so #draggable1, #draggable2, draggable3, ... all the way to 8
i then made an array and saved them into each array like this 8 times each draggable function represents numbers from 1 to 8 because we are adding pizza pies like fractions
<script>
var theimagestwo = new Array();
Draggablenumber[1] = $("#draggable1");
DraggableNumber[2] = $("#draggable2");
I do this until i fill up 8 draggable numbers in each array
So the logic is MyAnswer = WhichImage + WhichImage2 Then i have to check if DraggableNumber[MyAnswer] is dropped then i have the right answer...
How would i go about creating this feature??
Following your comment, this will be an easy task, you only need to follow these steps:
Create two random numbers contained in the slices array
Calculate the sum of these values
When you drop the number compare if this number is equal to the sum
of the slices
Here you have an example code:
HTML
<div id="slices">
</div>
<div id="options">
<div data-index="1">1</div>
<div data-index="2">2</div>
<div data-index="3">3</div>
<div data-index="4">4</div>
<div data-index="5">5</div>
<div data-index="6">6</div>
<div data-index="7">7</div>
<div data-index="8">8</div>
</div>
<div id="area">
drop area
</div>
jQuery UI
//---Vars
var slices = $("#slices");
var options = $("#options");
var area = $("#area");
var selected;
var result;
//---Array of images
var pizzas = [
{image: "http://s23.postimg.org/6yojml8vb/Pizza_One.png", value: 1},
{image: "http://s13.postimg.org/5d8zxnb2b/pizzatwo.png", value: 2},
{image: "http://s12.postimg.org/xfsxldqyx/pizzathree.png", value: 3},
{image: "http://s14.postimg.org/d6tdq0865/pizzafour.png", value: 4}
];
var total = pizzas.length;
//---Make boxes dragables
options.find("div").draggable();
//---When the boxes are dropped
area.droppable({
drop: function(event, ui){
if( Number( ui.draggable.attr("data-index") ) == result ){
alert("correct");
}else{
alert("incorrect");
}
}
});
//---Insert random pizza slices
function insertPizzas(){
selected = [];
result = 0;
//---Generate aleatory pieces
var rand
while(selected.length < 2){
//---Random value
rand = Math.floor( Math.random() * total );
//---Sum result
result += pizzas[rand].value;
selected.push( rand );
}
//---Clear the slices
slices.html("");
//---Add the new slices
selected.forEach(function(number){
var img = $("<img/>");
img.attr("src", pizzas[number].image);
slices.append(img);
});
}
insertPizzas();
jsfiddle

How to add dynamic decimal to another decimal in a div using JQuery

I need to be able to add a decimal from input to a decimal in a div. Here's my code below. Right now, it's just concatenating the two number next to each other. Thanks.
EDITED: Working code
<div id="addme">5.01</div>
<input type="text" id="anumber" value="">
<button id="add">Add Number to div</button>
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
//alert(number);
$('#addme').html(function(i, val) {
return (parseFloat(val) + number).toFixed(2);
});
});
Old Non-Working Code Below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="addme">5.01</div>
<input type="text" id="anumber" value="" />
<button id="add">Add Number to div</button>
<script type="text/javascript">
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number==''){
var number=0;
}
//alert(number);
$('#addme').html(function(i, val) {return val*1+number });
});
</script>
Since you're dealing with decimal numbers, use parseFloat():
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
$('#addme').html(function(i, val) {
return parseFloat(val) + number;
});
});​
http://jsfiddle.net/mblase75/47t7x/
UPDATE
Since you might introduce floating-point math errors (try inputing "0.6"), you should round it to a suitable number of decimal places before returning (2 if dealing with dollars and cents; 7 or more if dealing with other measurements):
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
$('#addme').html(function(i, val) {
return parseFloat((parseFloat(val) + number).toFixed(9));
});
});​
http://jsfiddle.net/mblase75/47t7x/1/
You should use parseInt() for this.
$('#addme').html(function(i, val) {return parseInt(val,10)+parseInt(number,10) });
Just make sure you're parsing the strings to actual numeric values.
function(i, val) {return parseFloat(val)*1+parseFloat(number) }
in your code it seem you want the sum, not concatenation
here is the code for sum, and you need to place that on a $(document).ready because your code was running before the objects were available.
$(document).ready(function() {
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number=='')
number=0;
var target=$('#addme');
target.html(1*target[0].innerHTML+1*number);
});
});
if you want concatenation just remove the 1*
To convert string to number you can use the trick with + before string value. It will convert string value to numeric. This code works fine:
$('#add').click(function() {
var number = +$('#anumber').val() || 0;
$('#addme').html(function(i, val) {
return (+val + number).toFixed(2);
});
});​
DEMO: http://jsfiddle.net/K9g49/
// On the click event of #add
$('#add').on("click", function(){
// n is equal to #anumber, or 0 if #anumber is blank
var n = $('#anumber').val() || 0
// Determine new HTML content for #addme
$('#addme').html(function(i,v) {
// Return the sum of n and v floated, to two decimal places
return ( parseFloat(n) + parseFloat(v) ).toFixed(2);
});
});​
Fiddle: http://jsfiddle.net/G8nka/1/

Categories

Resources