jQuery / javascript variable in if statement not working - javascript

I have a variable as such:
var is_last = $('.paging a:last').attr('rel');
this returns '-400' which is correct.
However, i need to add 200 to this so the answer is '-200'
if i do this:
var is_last = $('.paging a:last').attr('rel')+200;
the variable is now '-400200'
How can i pass the variable as a value?
A.

You need to parse the output of .attr(), it to an integer first using parseInt() so you're dealing with a number (and not a string), like this:
var is_last = parseInt($('.paging a:last').attr('rel'), 10) + 200;

I reckon that #Nick Craver is correct and that parseInt is the more correct answer, but as a quick-and-dirty alternative you can also convince javascript that a variable is a number and not a string by multiplying by 1:
var x = parseInt("-400", 10) + 200;
var y = ("-400" * 1) + 200;
alert(x);
alert(y);

Related

How to add one to a variable to make 2 not 11

Currently this makes 11. It's for a slideshow and the var "n" equals 1 by default
function forward() {
document.getElementsByClassName("img")[0].setAttribute("class","imgout");
setTimeout( function() {
var n1 = document.getElementById("img").getAttribute("data-number");
var n=n1+1;
document.getElementById("img").setAttribute("data-number", n);
document.getElementById("img").setAttribute("src", "images/" + n + ".jpg");
document.getElementsByClassName("imgout")[0].setAttribute("class","img");
}, 500)
}
Use parseInt():
var n = parseInt(n1, 10) + 1;
Instead of:
var n=n1+1;
When n1 will be a string, because it came from the DOM, you need to convert n1 to an integer. There are many ways to do this, and really you should probably use a regular expression to validate that n1 contains what you expect first, but that being said you can try any of the following:
var n=parseInt(n1, 10)+1;
var n=(n1*1)+1;
var n=(+n1)+1;
As an aside the regex for validating the input from the DOM might be something such as:
/^-?\d+$/
Use Number():
var n = Number("1");
FIDDLE
parseInt - good choice. Also you can do
var n = n-0+1
Just remember that of you have different types "+" will convert to string and "-" will convert to numbers
Convert n1 to number as it is a string like ~~n1. The ~~n1 form is good if you know you want an integer (a 32-bit integer).
Second way is to use Number() function i.e. Number(n1) will convert n1 value into a string.
var n=parseInt(n)+1;
Documentation
Fiddle

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

Removing an integer from an id

I have an id:
div id ="untitled-region-5"
I want to grab that id and remove 4 from it and then do some code with the new id.
So far I am trying something like this from reading about how to perform this:
var n = $(this).attr('id').match(/untitled-region-(\d+)/)[1];
But I don't know how to remove 4 from the integer.
It's still a string, that's why you can't easily use it in math. Some operations work, because they will implicitly convert the value to a number.
Use parseInt to explicitly do the conversion, so that you know what you have:
var n = parseInt($(this).attr('id').match(/\d+$/)[0]);
n -= 4;
var id = $("div").attr("id");
var n = parseInt(id.substring(id.lastIndexOf("-") + 1), 10);
I made a jsFiddle too: http://jsfiddle.net/YEWQQ/
<div id ="untitled-region-5">​
just take n and subtract 4
var n = $('div').attr('id').match(/untitled-region-(\d+)/)[1];
var newNumber = n-4;
$('div').attr('id','untitled-region-'+newNumber);

Performing mathematical operations on attribute value

I am attempting to perform mathematical operations with JavaScript on values obtained from an attribute. The attribute is created via a PHP loop. I will give an example of one of the html tags containing the attributes, but keep in mind that there are many of these tags which contain unique attribute values.
The HTML:
The JavaScript(jQuery):
$("a[href^='secondary_imgs.php']").click(function(){
var pageWidth = $(window).width();
var maxshadowWidth = (Math.floor(pageWidth * 0.91808874)) - 2;
var mWidth = $(this).attr("mwidth");
var maxSecondaryWidth = mWidth + 60;
alert (maxSecondaryWidth);
if(maxSecondaryWidth <= maxshadowWidth) {
var shadowWidth = maxSecondaryWidth;
} else {
var shadowWidth = maxshadowWidth;
}
var shadowboxrel = 'shadowbox;width=' + shadowWidth;
$(this).attr('rel', shadowboxrel);
The operation doesn't seem to be working, and I have a feeling it has to do with my lack of experience using mathematical operations in javascript. In this case, I think something is wrong with my method of using the attribute value, in the mathematical operation.
For example, the above width attribute is defined as 593. I define the maxSecondaryWidth as mWidth + 60. I fired an alert to see what value I was getting. It should have been shown as 653, yet the value that is 'alerted' is 59360. Obviously I don't understand how to add, as the + is concatenating the two values, as opposed to adding them together. Could it have to do with needing to transform the attribute value from a string into an integer?
You have to convert to a number using parseInt(), otherwise + will do string concatenation:
var mWidth = parseInt($(this).attr("mwidth"), 10);
If the attribute can also be a float, use parseFloat() instead of parseInt().
Do this to make sure mwidth is a number:
var mWidth = parseInt($(this).attr("mwidth"), 10);
Otherwise, + will perform a string concatenation. Alternatively, if you need mwidth to be a floating point number, do this:
var mWidth = parseFloat($(this).attr("mwidth"));
You can do a couple things:
parseInt(mWidth, 10); // int
parseFloat(mWidth); // float
Number(mWidth); // number
otherwise javascript will believe it's a string.
Some less common conversions:
mWidth | 0; // int (javascript bitwise operations are 32-bit signed intergers)
+mWidth; // force Number
i think that you must do something safer (as it is always better);
You should check if it is a number or not:
DOM:
JS:
$("a[mwidth]").each(function(){
var $attr = $(this).attr('mwidth');
if(!isNaN($attr)){
sum += (parseInt($attr));
}
});
If you remove the condition the results will be NaN
Take a look at : http://jsfiddle.net/zVwYB/

How to add together numerical values that are stored in strings?

I'm trying to add 1 to my JavaScript variable, but the following code doesn't give expected results:
var val1 = document.getElementById('<%= rng1.ClientID %>');
var val2 = val1.value + "1";
alert(val2.value);
How can I do this?
you can use the function parseInt() to transform the string stored in val1.value into a number:
var val2 = parseInt(val1.value) + 1;
Note that Number(val1.value) will also convert your value into a number.
-edit-
As yc suggest, is highly recommended to use parseInt(val1.value, 10) + 1; because if your string starts with a "0" the string is interpreted as octal. eg. parseInt("0123") == 83 and not 123
The simplest and also preferred way would be to use + to cast to a number.
Examples:
+'234'; // 234
+'042'; // 42! It does not convert to octal
In your case:
var val1 = +(document.getElementById('<%= rng1.ClientID %>').value); // () added just for the looks
var val2 = val1.value + 1; // if val1 is 5, val2 will be 6 hooray!
alert(val2); // just val2, since it's a plain number not an html input element
parseInt($('.scpContainer').height()+200)
you must add number, so try it without quotes :-)
In an external JavaScript file you can't use the <%=ControlID.ClientID %> to get the client id.
If there you using an external JavaScript file you need to pass client id value to that function.

Categories

Resources