Add value of two variables into one variable - javascript

Quick javascript question. I am trying to create a variable that equals the width of two other variables. I have:
var mainNavWidth = mainNav.width();
var remainWidth = $('#header .main-wrap').css("margin-right");
var subNavWidth = remainWidth + mainNavWidth;
The first two variables are spitting out numbers as I would like them two, but the third variable is not working. I know this has to be an easy fix, I'm just not sure how. Any help is much appreciated

you need to parseInt() the margin one, since margin will/can return string like "0px"/"10px" etc so you need to convert it into integar before adding
var remainWidth = parseInt($('#header .main-wrap').css("margin-right"));

var remainWidth = $('#header .main-wrap').css("margin-right");
The .css() method returns a string, for instance "20px" or "100%" or "inherit", so it's not always a number !
var remainWidthAsInteger = parseInt($('#header .main-wrap').css("margin-right"));
var remainWidth = (remainWidthAsInteger == NaN) ? 0 : remainWidthAsInteger;

jQuery returns the value with 'px' so :
var mainNavWidth = mainNav.width();
var remainWidth = $('#header .main-wrap').css("margin-right");
var subNavWidth = parseInt(remainWidth) + parseInt(mainNavWidth);

Related

Subtract 1 from variable jQuery

Having some trouble getting this right. I'm very new to jQuery, so trying to get better and learn.
Currently I am getting 2 different values from a html table using the following code
var sellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var buyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
These both output a value such as $13,000,000
I am then wanting to subtract 1 from these values (making it $12,999,999) before pasting them to an input as such
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
However, I am having some trouble with how to subtract $1 from these.
I tried using sellPrice--; but without success.
I've also tried adding - 1; at the end of each variable, but did not succeed either.
I tried to test something like this, but did not work either.
var minusOne = -1;
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = (getCurrentSellPrice - minusOne);
var buyPrice = (getCurrentBuyPrice - minusOne);
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);`
Trying my best to familiarize myself with jQuery :)
Any help is much appreciated!
Solved using this
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = Number(getCurrentSellPrice.replace(/[^0-9\.]+/g,"")) - 1;
var buyPrice = Number(getCurrentBuyPrice.replace(/[^0-9\.]+/g,"")) + 1;
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
Since your numbers contain currency symbol and are strings, you need to convert them to proper numbers before subtracting them. See the answer below.
How to convert a currency string to a double with jQuery or Javascript?

Manipulation data on javascript

I have some codes like this
var f = document.frmR5B075;
var str = f.cbo_BilServProvCodeHidden.value;
var afterDash = str.substr(str.indexOf("-") + 1);
And i want put afterDash value back to f.cbo_BilServProvCodeHidden.value. I tried use f.cbo_BilServProvCodeHidden.value = afterDash; seems not working / cannot get the value. Any Solution ? Thanks
f.cbo_BilServProvCodeHidden.value = afterDash seems to work for me.
Here is the demo

How to fix Javascript NaN issue?

Here is my code
var total_center_buttons=$('.center_button').length;
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height=total_center_buttons + center_button_height;
alert(total_center_button_height);
Here total_center_button value =3
and center_button_height is 40 while alerting them separately.It returns NaN. I tried ParseInt also but result is same.Please suggest me the solution.Thanks in advance.
Krishna
We have to guess, since you haven't quoted the DOM, but my guess is that $('.center_button:first-child') doesn't match any elements. Calling height() on an empty set returns undefined. When you try to add it to the number from the previous line, you get NaN.
I suspect you didn't want :first-child, but rather
var center_button_height=$('.center_button').first().height();
...but again without seeing the DOM, it's hard to say. To avoid repeated DOM lookups, you'd do this:
var buttons = $('.center_button');
var total_center_buttons = buttons.length;
var center_button_height = buttons.first().height();
var total_center_button_height = total_center_buttons + center_button_height;
alert(total_center_button_height);
.center_button:first-child will only match an element that both has the class center_button and is the first child of its parent element. My suggestion above is based on the assumption that you really wanted the first of the buttons, and that the buttons aren't the first thing in their parent.
Finally: That + in
var total_center_button_height = total_center_buttons + center_button_height;
looks suspicious. Again without seeing the markup it's hard to say, but you may have meant * there.
Mate,
there's a typo in your post. Notice the code line where you assign the value to total_center_button_height
var total_center_button_height = center_button_height + total_center_button_height;
That's where the problem is, the variable to the right of the addition operation (total_center_button_height) does not exist yet. Replace that line with...
var total_center_button_height = center_button_height + total_center_buttons;
Pretty straight forward
Hope it helps
Leo
may be you need to write this
var total_center_button_height=center_button_height + total_center_buttons;
alert(total_center_button_height);
you can check for "isNaN" function, this is to check whether the parameter is number or not.
Try this:
$(function(){
var total_center_buttons = $('.center_button').length > 0 ? $('.center_button').length : 0;
if(total_center_buttons !=0){
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height = center_button_height + total_center_button_height;
alert(total_center_button_height);
}
});
you are doing this:
var total_center_button_height=center_button_height + total_center_button_height;
i.e. total_center_button_height is used in the same line where it is declared. At this time it is undefined.
i guess, you should be doing:
var total_center_button_height=center_button_height + total_center_buttons;
Try something like this:
var total_center_buttons=$('.center_button').length;
if (typeof total_center_buttons != 'undefined') {
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height=total_center_buttons + center_button_height;
alert(total_center_button_height);
}

Check if number is between 2 values

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)

Get last string from URL with jQuery

Im trying to get the last string from a URL for example...
http://www.mywebsite/blog/this-post
I want to use jQuery to get 'this-post'
Ive the following...
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/');
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[1]+'.jpg');
})
only it doesn't work and I presume thats because I have multiple '/' within the URL, any idea how to target just the last?
Hope this makes sense!
This is precisely what .pop() is made for:
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/').pop();
$(this).attr('src','/lic/wp-content/uploads/2012/01/' + foo + '.jpg');
});
Don't use the element with index 1 of foo, but the last one:
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[foo.length-1]+'.jpg');
Splitting with "/" will give you the array:
foo[0] = "http:"
foo[1] = ""
foo[2] = "www.mywebsite"
foo[3] = "blog"
foo[4] = "this-post"
If you want to get the last item regardless of the size of the array do:
foo[foo.length - 1]
or as Joseph mentioned: foo.pop()
Following your example you need the last part of the splits:
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/');
var last = foo.length - 1;
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[last]+'.jpg');
})
var foo = $(this).parent().attr('href').replace(/^.*\\/, '');

Categories