Simple Math with JS - javascript

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>

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));
});
});

Get only text value where user click it

Get only text value where the user clicked it
HTML code
<body>
<div id="test">
<pre>
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
<pre>
</div>
</body>
In the above code I am using pre tag, I have a long list of user so I want every user on next line
When the user click on zelketg, only I want zelketg under javascript alert box instead of whole text.
I tried the below JavaScript but it didn't works, It give me the whole text under div
$(document).click(function(event) {
var text = $(event.target).text();
alert(text);
});
Contents of pre tag are not identifiable as an individual nodes, so you need to do some pre-conditioning so that they can be identified as an individual nodes.
var preNode = document.querySelector( "pre" );
function preCondition()
{
var text = preNode.innerText;
preNode.innerHTML = text.split("\n").map( s => "<div>" + s + "</div>" ).join( "" );
}
preCondition();
Now you can add a click event handler on the pre-tag
preNode.addEventListener( "click", function(){
console.log(event.target.innerHTML);
});
Demo
var preNode = document.querySelector( "pre" );
function preCondition()
{
var text = preNode.innerText;
preNode.innerHTML = text.split("\n").map( s => "<div>" + s + "</div>" ).join( "" );
}
preCondition();
preNode.addEventListener( "click", function(){
console.log(event.target.innerHTML);
});
<div id="test">
<pre>
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
</pre>
</div>
Try as follows might help
$(document).click(function(event) {
var text = $(event.target).text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="test">
<pre>
<i>zelketg 1</i>
<i>gcaotydv 14</i>
<i>cdbot_i 11</i>
<i>pacdhss12 1</i>
<i>boters 1</i>
<pre>
</div>
</body>
Go over each line beforehand and turn them into span elements so you can handle them separately.
var lines = $("#test pre").text().split("\n");
$("#test pre").empty();
$.each(lines, function(n, elem) {
$("#test pre").html( $("#test pre").html()+'<span>'+elem+'</span><br>');
});
$('#test pre').click(function(event) {
var text = $(event.target).text();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="test">
<pre>
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
<pre>
</div>
</body>
Post-Fork of #Nisal Edu
You can replace your whole pre element as the following example for this you don't need any other library alike.
<body>
<div id="test">
<pre id="test_pre">
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
</pre>
</div>
</body>
<script>
function getText(elem)
{
var user_name = elem.childNodes[0].innerHTML;
var user_id = elem.childNodes[1].innerHTML;
alert(user_name+","+user_id);
}
(function(){
var pre_tag = document.getElementById("test_pre");
var pre_text = pre_tag.innerHTML;
var pre_elem = pre_text.split('\n');
var doc_string ="" ;
for(item in pre_elem)
{
var arr = pre_elem[item].trim().replace(" ",",").split(",");
doc_string += "<p onclick='javascript:return getText(this);'><span>"+arr[0] +"</span><span> "+ arr[1] +"</span></p>";
}
document.getElementById("test_pre").innerHTML = doc_string;
})();
</script>

Trim number before decimal point

<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
I just want the value £123 to show, need correct Javascipt to "trim" the number and not round it down or up. I've seen a few ways on here but none that target .class name, in my case .numTxt
If somebody can do me a quick fiddle I would be most appreciative!
You can use .text() call back function to modify the old text with new text:
$('li.numTxt').text(function(i,val){
return val.split(".")[0];
});
Working Demo
Here you are:
alert(document.querySelector('li').innerText.replace(/\.\d*/,''));
Hope this help.
You can do this easily with split()
var str = "£123.99"
var res = str.split(".");
//res is now an array consisting of "£123" and "99"
Working Example:
$('button').click(function(){
var str = $('#inp').val();
var res = str.split(".");
$('#output').html(res[0]);
});
input, button, div { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inp" value="£123.99" />
<button>Split At Decimal</button>
<div id="output"></div>
Just use this Regex /\.\d+/:
$.fn.trimDecimal = function(){
$(this).text(function(a, text){
return text.replace(/\.\d+/,"")
})
}
$(".numTxt").trimDecimal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£83.45</li>
To truncate a decimal number, you can do it in this way:
var num = "123.99";
num = +num | 0;
console.log(num)

My JS/JQuery wont update my text field value

Hey guys I'm still fairly new to js and JQuery so I really need some help. I've tried several ways to do this. I basically need the value of my text box increased by 1 when a user clicks the plus button, and decreased by 1 when they click the minus button. I haven't coded for the minus as I haven't figured out the plus. My $('#itemQuant1').val(+1); call works, but stops at 1. Here is my js:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var current_count = $('#itemQuant1').val();
var plus_count = current_count + 1;
var minus_count = current_count - 1;
//var minusCount = document.getElementById('minusItem').value;
$("#plusItem1").on('click', function(){
current_button = $(this);
if (current_button.attr('id') == "plusItem1")
{
$('#itemQuant1').val(+1);
//current_count.val() + plus_count;
//plus_count.val() + 1;
//$('#itemQuant1').value = current_count.value + 1;
}
});
});
</script>
Here is the html:
<body>
<div>
<table style= "border:solid;border-width:thin;">
<tr>
<td style= "border:solid;border-width:thin;"><p><input class"comfirmItem" type="checkbox">1-FLUE CONNECTOR ASSEMBLY PACKAGE (0005812) +$665.10<button id="plusItem1" class="more_Item" style="float:right;">+</button><button id="minusItem" class="less_Item" style="float:right;">-</button><input id="itemQuant1" class"itemCount" type="textbox" value=0 style="width:30px;text-align:center;margin-left:5px;margin-right:5px;float:right;"></p></td>
</tr>
<tr>
<td style= "border:solid;border-width:thin;"><p><input class"comfirmItem" type="checkbox">2-DUCT BOX ASSEMBLY (0005875) +$305.01<button id="plusItem" class="more_Item" style="float:right;">+</button><button id="minusItem" class="less_Item" style="float:right;">-</button><input id="itemQuant2" class"itemCount" type="textbox" style="width:30px;text-align:center;margin-left:5px;margin-right:5px;float:right;"></p></td>
</tr>
</table>
</div>
</body>
</html>
You just need to do this - http://jsfiddle.net/jayblanchard/rCM5d/
$('#itemQuant1').val( parseInt($('#itemQuant1').val()) + 1);
For up and down buttons it might be an idea to wrap all the button logic together like so: http://jsbin.com/kikitule/1/edit
Your HTML would look like this:
<button class="items-button" data-sum="1" data-target="#itemQuant1">+</button>
<button class="items-button" data-sum="-1" data-target="#itemQuant1">-</button>
<input id="itemQuant1" class="itemCount" type="textbox" value=0>
And JQuery like this:
$(document).ready(function(){
$(".items-button").on('click', function(){
var $button = $(this);
var $quantity = $($button.attr('data-target'));
var sum = parseInt($button.attr('data-sum'), 10);
var total = parseInt($quantity.val(), 10) + sum;
if (total < 0) {
total = 0;
}
$quantity.val(total)
});
});

jquery two replace functions

I am not sure why item count parentheses aren't being removed in this tiny fiddle example.
EDIT: Here is my result from looking at the working answer.
$.fn.itemcount = function(){
var text = $(this).text();
text = text.replace("(","").replace(")","");
$(this).text(text);
};
$("#prc").itemcount();
$.fn.sidecartcost = function(){
var el = $(this);
var text = $(this).text();
text = text.replace("Your sub total is", "").replace(". ", "");
$(this).text(text);
};
$('.SideCartCost').sidecartcost();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="prc">(7 Items)</div>
<div class="blank">Woo</div>
<div class="SideCartCost">Your sub total is $300.03. </div>
you are not replacing the html/text of the div like so http://jsfiddle.net/x5jeL/1/

Categories

Resources