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?
In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place.
Adding Numbers and StringsJava uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated.
A string represents alphanumeric data. This means that a string can contain many different characters, but they are all considered as if they were text, even if the characters are numbers. A string can also contain spaces.
The string and the number are presented as one field. Note that you’re not limited to just one string and one number – the CONCAT () function can accept up to 254 arguments (i.e. you can join up to 254 strings/numbers together.
Note that you’re not limited to just one string and one number – the CONCAT () function can accept up to 254 arguments (i.e. you can join up to 254 strings/numbers together. Also note that CONCAT () implicitly converts all arguments to string types before concatenation.
This article presents six ways to concatenate strings with numbers using T-SQL. The most obvious (and possibly the best) way to concatenate a string and a number is to use the CONCAT () function. This allows you to provide the string and the number as two separate arguments. SQL Server will then concatenate them, and your concatenation is complete.
You can use an array formula to sum the numbers based on their corresponding text string within the cell, please do as follows: 1. First you can write down your text strings you want to sum the relative numbers in a column cells. 2.
parseInt($('.scpContainer').height()+200)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With