I am currently building a filter based on div class's and contents.
I was wondering if it is possible to pass a string like follows into a function:
"£0.01 - £100.01"
and then have the function show all div's where the html of that div is between this range
so say I have a div with a class of "price" and its contents were: £10.30
from running this function and passing the string of "£0.01 - £100.01" into it it would hide all div's similar to how I have done it in the js below then only show the div's where the div class "price"'s contents were within the selected price range.
I have managed to do something similar with a brand filter which I will provide here:
function brand(string){
var brand = string;
$('.section-link').hide();
$('.section-link').children('.brand.' + brand).parent().show();
if (brand == "All Brands"){
$('.section-link').show();
}
}
Any general advice or code is greatly appreciated to help achieve this :)
Thanks,
Simon
Edit:
Target div example:
<div class="section-link">
<div class="price"> £56.99</div>
</div>
Reply's are helping a lot, the filter function looks awesome so thanks for pointing that out.
I am just trying to find a way to split the initial string being past in, into two values one low and one high as well as stripping the £ signs
Edit:
managed to split the original string:
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
alert(rangearray[0]);
alert(rangearray[1]);
FINAL EDIT:
From the reply's I have kind of been able to make a function, however it is not entirely working :) can anyone spot what I have done wrong?
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0];
high = rangearray[1];
$('.section-link').children('.price').each(function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
if (low <= divprice && high >= divprice){
$(this).parent().show();
}
})
}
Okay its working, I had spaces in my string. The final function (although messy :P) is:
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0].toString();
high = rangearray[1].toString();
lowmain = low.replace(/ /g,'');
highmain = high.replace(/ /g,'');
$('.section-link').children('.price').each(
function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
var maindivprice = divprice.replace(/ /g,'');
if (lowmain <= maindivprice && highmain >= divprice){
$(this).parent().show();
}
})
}
I'd use a function like this one, where range is the string you gave
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
You can use jQuery's build in filter() function, and write a filter with the condition you described.
First, you should hide all the items with any price.
$(".price").parent().hide();
Then, you can filter all the items with in-range prices and show them:
$(".price").filter(function(){
var $this = $(this);
var value = $this.val();
return (value >= minNumber && value <= maxNumber); // returns boolean - true will keep this item in the filtered collection
}).parent().show();
Use jQuery's filter()
An example -> http://jsfiddle.net/H6mtY/1/
var minValue = 0.01,
maxValue = 100.01;
var filterFn = function(i){
var $this = $(this);
if($this.hasClass('amount')){
// assume that text is always a symbol with a number
var value = +$this.text().match(/\d+.?\d*/)[0];
if(value > minValue && value < maxValue){
return true;
}
}
return false;
};
// apply your filter to body for example
$('#target span')
.filter(filterFn)
.each(function(i,ele){
// do something with the selected ones
$(this).css('color','red');
});
I would go by something like:
Get all the divs that have prices.
Iterate through all:
Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
If they are just go to the next (use continue maybe)
Else (not in the range) add a class like .hide so it can be blended through css (or just use the blend function from jquery)
Related
var result="stackoverflow";
var string="22342st";
if(more than 3 letters)
{
var new=data;
}
1)how I can get variable if only have more than
using match() (function ) in javascript
2)what if I do getting variable in for time delay
some (because of TCP connection)
Does anyone have an idea?
you can use .length property to check string length is greater than 3 or not.
var result = "stackoverflow";
if(result.length > 3)
{
//Your business logic goes here
}
if you want to check only character counts in string is greater than three then you can try below code
var input = "45749ce";
var result = input.match(/[a-zA-Z]/gi);
if(result.length > 3)
{
//Your business logic goes here
console.log(`${result} length is greater than 3`);
}
That should work
var myRegEx = /[a-zA-Z(.+)]{3}/g;
var myString="22342st";
if(myString.match(myRegEx)!==null)
{
}
Also
myString.match(myRegEx)
will return an array of matched values, so you can work with them if needed.
To find the more than three letter in variable using match you have to need regex
([a-zA-Z0-9)]){3,}
code how looks like
var result="stackoverflow";
var string="22342st";
var res = string.match(/([a-zA-Z0-9)]){3,}/g);
if(res!=null){
//here what you want
}
I'm trying to create a script that get some values from several selectboxes and then do some math with them.
The problem is that the script need to be placed in a SaaS enviroment so my options of doing stuff are every limited. The way described below is the only way to do this.
The problem I'm facing is that I can receive the correct values from the selectboxes but I can't convert them to 2 decimals. Further I can't get the initial value adviesprijs converted to just eg. 1500 instead of 1.5 or 1.500.00. I really can't see what I'm doing wrong.
I've created a fiddle here I think that describes my problem best!
My script
function update_amounts() {
var perc = '10' || 0; //this is a value from a Twig tag. Not relevant for question!
var korting = ((100-perc)/100);
var adviesprijs = '€1.500,00'.replace(/[^\d.]/g, ''); //gives 1.5 or 1.500.00 etc..
var adviesprijsValue = parseFloat(adviesprijs) || 0;
var sum = 0.0;
$('#product_configure_form .product-configure-custom-option select').each(function () {
var optionText = $(this).find('option:selected').text();
var matches = optionText.match(/\(([^)]+)\)/g) || [];
if (matches.length > 0) {
var priceText = matches[matches.length - 1];
if (priceText.indexOf("€") > -1) {
var priceClean = priceText.replace(/[^0-9\+\-\.\,]/g, '');
var priceValue = parseFloat(priceClean) || 0;
sum += priceValue;
}
}
});
var sum2 = sum+adviesprijsValue;
var sumBtw = (sum2*1.21).toFixed(2);
$('#amount').text('€' +sum2);//
$('#amountBtw').html('(€'+sumBtw+' - Incl. 21% BTW)');//.toFixed(2)
}
$(document).ready(function(){
$( "#product_configure_form").on("change", ".product-configure-custom-option select", update_amounts);
});
The HTML is pretty long so best is to take a look at the Fiddle.
Can anybody help me to make a correct calculation...?!
Thx in advance
Your conversion from Dutch formatting to normal float formatting is incorrect.
Consider using:
.replace(/[^\d,]/g,"").replace(",",".")
Working example: http://jsfiddle.net/pgaphma3/3/
EDIT
To allow also a plus or minus sign use /[^\d,\-+]/g
This probably is a very easy solution, but browsing other questions and the internet did not help me any further.
I made a javascript function which will give me a random value from the array with its according points:
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
document.getElementById("Points").innerHTML += punten;
}
I've added a += punten so i can see that it works correctly. It shows me all the point in the div with the id Points.
But what i wanted to do is count it all together so if i were to draw a 4, King and a 10 it should show 24 instead of 41010.
Thanks in advance! And if you're missing any information please let me know
Currently you are just adding strings together, which concatenate (join together) hence why you end up with 41010. You need to grab the current innerHTML (total) and use parseInt() to convert from a string to a number, then add your new cards that have been chosen, then assign this new value to the innerHTML of your element.
Try the following
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
var total = curPoints + parseInt(punten, 10);
document.getElementById("Points").innerHTML = total;
}
More info on parseInt() here
EDIT
I've added this line -
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
Which will try and convert the innerHTML of the "Points" div, but if it is empty (an empty string converts to false) then curPoints will be equal to 0. This should fix the issue of the div being blank at the start.
innerHTML is a string and JavaScript uses + for both string concatenation as numeric addition.
var pointsInHtml = parseInt(document.getElementById("Points").innerHTML, 10);
pointsInHtml += punten;
document.getElementById("Points").innerHTML = punten;
The second parameter 10 of the parseInt method is usually a good idea to keep there to avoid the function to parse it as an octal.
It might be easier to keep a points variable and only at the end put it in the #Points container, that would make the parseInt no longer necessary
innerHTML will be a string, so you need to convert it into an integer prior to adding the card value :)
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1],
curPunten = parseInt(document.getElementById('Points').innerHTML);
document.getElementById("Points").innerHTML = curPunten + punten;
}
I have a string and in some instances it can be over 150 chars in length(including space and special chars). I was just gonna take the curr length, minus 150 (if greater than 150) and with the remember, shave off a part of the string. I am curious if there is a robust way to do it? The issue is, I don't necessarily want to shave the end. I want to shave the part that resides in a "span" with a certain ID. I want to have that string section and append with "...". So, I have this.
For example. I have.
<div id="divid">
Funny thing is, I went to the store <span id="spanid">on a Tuesday afternoon while the sun was in the sky</span> and rode home with excitement and glee. Did I say it was Tuesday?
</div>
var txtcount = jQuery('#divid').text().length;
var spanidcount = jQuery('#spanid').text().length;
if(txtcount > 140){
var tocut = txtcount - 140;
// here I would reduce the contents of spanid so that the total string count is 140 or less. and have spanid end with "..." - with the ... counting toward the total of 140.
}
A cleaner way would be to use CSS text-overflow:ellipsis on your div. Sample fiddle.
The advantage of this way that you don't trust font size and variant letter width to not screw you up. You always cut the text exactly where you need it. And if div is resized, the ellipsis is automagically adjusted to the right length.
The best thing to do is implement a truncate function. You don't have to extend the String prototype, but I did in this case. :P
http://jsfiddle.net/j89em/1/
String.prototype.truncate = function (len, trail) {
len = len || 10; // default to 10
trail = trail || '...';
return len < this.length ? this.substring(0, len - trail.length) + trail : this;
};
var $div = $('div'),
$span = $div.find('span');
$span.text($span.text().truncate(25));
So you could actually test the total test length and apply the truncate method if needed.
if ($div.text().length > 140) {
$span.text($span.text().truncate(25));
}
You can do it like this:
html:
<p>Funny thing is, I went to the store <span>on a Tuesday afternoon while the sun was in the sky</span> and rode home with excitement and glee. Did I say it was Tuesday?</p>
<button>Reduce</button>
jQ:
var reduceStr = function(str, maxLen) {
return str.substr(0, maxLen-1) + (str.length > maxLen ? '...' : '');
};
$('button').click(function(){
$('span').text(reduceStr($('span').text(), 30));
});
Include this (plug-in) in a script tag or linked from an external .js file sometime after jQuery has been loaded:
(function($) {
$.fn.trimFluff = function(options) {
var settings = $.extend({
'childSelector': '#spanid',
'maxLength': 140
}, options);
return this.each(function() {
var container = $(this);
var child = $(settings.childSelector);
var containerLen = container.text().length;
var childLen = child.text().length;
var fluffToTrim = containerLen - settings.maxLength;
if (containerLen > settings.maxLength) {
if (fluffToTrim > childLen) { //'fluffToTrim' is larger than the child contents...
$(this).find(settings.childSelector).remove(); //remove child
containerLen = container.text().length; //recalc new length
fluffToTrim = containerLen - settings.maxLength; //recalc 'fluffToTrim'
if (containerLen > settings.maxLength) {
//remove "offending length" characters + 3 for the ellipsis and replace with the ellipsis
container.text(container.text().substring(0, containerLen - fluffToTrim + 3) + '...');
//string is now under (or equal to) 140 characters
}
} else {
//remove "offending length" characters + 3 for the ellipsis, from the child, and replace with the ellipsis
child.text(child.text().substring(0, childLen - fluffToTrim + 3) + '...');
}
}
});
};
}(jQuery));
Then call it like so:
$('#divid').trimFluff();
or pass in an options object. There are two options, childSelector which accepts any valid jQuery selector (or element, or jQuery object) and maxLength (which I hope is self-explanatory :) ).
Examples:
$('#divid').trimFluff({childSelector: 'span', maxLength: 150});
$('#divid').trimFluff({childSelector: $('#spanid'), maxLength: 140});
$('#divid').trimFluff({childSelector: 'span#spanid.customClass', maxLength: 160});
var s = document.getElementById('spanid');
$('divid').trimFluff({childSelector: s);
This will trim from the child first, keeping the left side, and if the text to to cut is larger than the child itself, it will remove the child entirely and trim the remaining contents of the div (or other container) until the text is less than the maxLength.
This does not do virtually any error checking, but it will work with any jQuery object where the text() function does something.
Have fun with it.
I need a JavaScript function that will parse the HTML source of the page from which it is called as an external script, retrieve any dollar amounts in the source, and set the highest dollar amount to a JavaScript variable.
So for instance, if the page contains the text, "Your product is $40.32 and tax is $4.50, your total is $44.82.", the JS should parse those values and set $44.82 to "var total" as the highest amount. Possible?
Thanks based on the tips I wrote this, which works. Hopefully yours or my solution will help others:
var dochtml = document.getElementsByTagName('body')[0].innerHTML;
dochtml = dochtml.replace(/(\r\n|\n|\r)/gm,"");
var price_array = new Array;
var pattmatch = /(\$(([0-9]{0,1})?.[0-9]{1,2}))|(\$([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(.[0-9]{1,2})?)/gi;
price_array = dochtml.match(pattmatch);
if (price_array) {
for (var i=0; itotal || !total) {
var total=price_array[i];
}
}
document.write(total);
}
You can grab the HTML of the current document from the Javascript by grabbing the document's innerHtml, something like:
document.getElementsByTagName('html')[0].innerHTML
Then you can pull out all the currency values with a regular expression, something like:
((\$(([0-9]{0,1})?\.[0-9]{1,2}))|(\$([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(\.[0-9]{1,2})?))
Just loop through all the matches and every time the current match is greater than the value in total, set total to the current match.
Disclaimer: That regex was pulled from the community on http://gskinner.com/RegExr/ and I can't promise you it's 100% fullproof.
Take a look at this question here, which demonstrates how to extract numbers from a String: Javascript extracting number from string
Try this:
// get all content from page
var content = document.body.innerHTML;
// create an array of all dollar amounts in the content
arrayNum = content.match(/\$[0-9]+\.[0-9]+/g);
// display array of numbers
console.info(arrayNum);
var high = 0;
for(var i = 0; i < arrayNum.length; i++) {
// remove the dollar sign and cast the string to a float
arrayNum[i] = parseFloat(arrayNum[i].substring(1));
// get the high value - O(n) operation
high = ( (arrayNum[i]) > high ) ? arrayNum[i] : high;
}
alert("High value = " high);