473,394 Members | 1,735 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

incrementing variables in javascript

Hello
I have the following code, where clicking yh1r is supposed to move h1 10px
down and update the value of yh1 by 20 each time its clicked.
what the code actually does is NOT move h1 and instead of incrementing yh1
from 0 to 20 to 40 etc it doubles it and appends it to the original value
each time eg 0 to 20 to 4020 to 804020 to 160804020

<div id='h1' style='position:absolute; top:<?php echo $yh1/2;?>px; <?php
$h1; ?></div>
<input name="yh1" id="yh1" type="text" class="BodyText" value="<?php echo
$yh1; ?>" size="1">
<input name="yh1r" id="yh1r" type='button' class="BodyText"
onClick="yh1move(10)" value='>'>
function yh1move(amount) {
var yh1val=document.form2.yh1.value;
yh1val += amount;
h1.style.top =yh1val+'px';
document.form2.yh1.value = yh1val*2;
}
but when I give yh1val a numerical value to start, as below it works

var yh1val = 0;
function yh2move(amount) {
yh1val += amount;
h2.style.top =yh1val+'px';
document.form2.yh2.value = yh1val*2;
}
can anyone see what the problem is?
Ian
Aug 9 '06 #1
8 2359

mantrid wrote:
Hello
I have the following code, where clicking yh1r is supposed to move h1 10px
down and update the value of yh1 by 20 each time its clicked.
what the code actually does is NOT move h1 and instead of incrementing yh1
from 0 to 20 to 40 etc it doubles it and appends it to the original value
each time eg 0 to 20 to 4020 to 804020 to 160804020

var yh1val=document.form2.yh1.value;
yh1val += amount;
h1.style.top =yh1val+'px';
document.form2.yh1.value = yh1val*2;

can anyone see what the problem is?
Ian
When you get the value from your form, the value is a string.
Therefore, when you thought were you adding, you were really in fact
concatenating strings. Converting the value to a numerical form will
fix this.

Aug 9 '06 #2
Thaks Web that did it.
Im suprised that it can tell an integer automatically
"web.dev" <we********@gmail.comwrote in message
news:11**********************@75g2000cwc.googlegro ups.com...
>
mantrid wrote:
Hello
I have the following code, where clicking yh1r is supposed to move h1
10px
down and update the value of yh1 by 20 each time its clicked.
what the code actually does is NOT move h1 and instead of incrementing
yh1
from 0 to 20 to 40 etc it doubles it and appends it to the original
value
each time eg 0 to 20 to 4020 to 804020 to 160804020

var yh1val=document.form2.yh1.value;
yh1val += amount;
h1.style.top =yh1val+'px';
document.form2.yh1.value = yh1val*2;

can anyone see what the problem is?
Ian

When you get the value from your form, the value is a string.
Therefore, when you thought were you adding, you were really in fact
concatenating strings. Converting the value to a numerical form will
fix this.

Aug 9 '06 #3
mantrid wrote:
Thaks Web that did it.
Im suprised that it can tell an integer automatically
Please don't top-post here. Reply below a trimmed quote of what you
are replying to.

JavaScript doesn't "tell an integer" automatically - it follows strict
rules on how to apply operators to variables.

The "+" operator is overloaded, it can mean (amongst other things)
arithmetic addition or string concatenation. Variables in JavaScript
aren't typed, so in order to work out how to apply the "+" operator in
a given situation the script engine looks at the values of the
variables that the "+" operator is applied to. It works from left to
right evaluating the result as it goes. If any variable is a string,
concatenation is inferred from that point on and a string is returned,
even if the remaining variables are numbers.

If all the variables are numbers, then addition is inferred and a
number is returned. If any of them are something other than string or
number primitives, other rules apply (read the relevant part ECMAScript
Language spec, I'm not going to cover them all here).

e.g.:

var a = "1"; // string
var b = 2; // number
var c = 4; // number

alert( a + b ) // since a is a string, "12" will be displayed
alert( b + c ) // b and c are both numbers, so "6" will be displayed
alert( a + b + c ) // a is a string, so "124" is displayed.
alert( b + c + a ) // b and c are added. Since a is a string the
// result is converted to a string, a is
// concatenated and "61" is displayed.
alert( b + c + a + c + b ) // shows 6142

The simplest way to convert a string to a number is to prefix it with
'+' as a unary operator (I did say it was overloaded :-) ):

alert( +a + b + c) // shows 7
alert( b + c + +a) // shows 7
HTH
--
Rob

Aug 10 '06 #4

"RobG" <rg***@iinet.net.auwrote in message
news:11**********************@p79g2000cwp.googlegr oups.com...
mantrid wrote:
Thaks Web that did it.
Im suprised that it can tell an integer automatically

Please don't top-post here. Reply below a trimmed quote of what you
are replying to.

JavaScript doesn't "tell an integer" automatically - it follows strict
rules on how to apply operators to variables.

The "+" operator is overloaded, it can mean (amongst other things)
arithmetic addition or string concatenation. Variables in JavaScript
aren't typed, so in order to work out how to apply the "+" operator in
a given situation the script engine looks at the values of the
variables that the "+" operator is applied to. It works from left to
right evaluating the result as it goes. If any variable is a string,
concatenation is inferred from that point on and a string is returned,
even if the remaining variables are numbers.

If all the variables are numbers, then addition is inferred and a
number is returned. If any of them are something other than string or
number primitives, other rules apply (read the relevant part ECMAScript
Language spec, I'm not going to cover them all here).

e.g.:

var a = "1"; // string
var b = 2; // number
var c = 4; // number

alert( a + b ) // since a is a string, "12" will be displayed
alert( b + c ) // b and c are both numbers, so "6" will be displayed
alert( a + b + c ) // a is a string, so "124" is displayed.
alert( b + c + a ) // b and c are added. Since a is a string the
// result is converted to a string, a is
// concatenated and "61" is displayed.
alert( b + c + a + c + b ) // shows 6142

The simplest way to convert a string to a number is to prefix it with
'+' as a unary operator (I did say it was overloaded :-) ):

alert( +a + b + c) // shows 7
alert( b + c + +a) // shows 7
HTH
--
Rob
I used
parseInt(myvar).
Is
+myvar better, or is there no difference?
Ian
Aug 10 '06 #5
mantrid wrote:
"RobG" <rg***@iinet.net.auwrote in message
[...]
The simplest way to convert a string to a number is to prefix it with
'+' as a unary operator (I did say it was overloaded :-) ):
[...]
>
I used
parseInt(myvar).
Is
+myvar better, or is there no difference?
You should always use parseInt() with a radix - assuming you want base
10:

parseInt(myvar, 10);

otherwise strings with leading zeros will be inerpreted as octal, try:

alert(
'parseInt(\'08\'): ' + parseInt('08')
+ '\nparseInt(\'019\'): ' + parseInt('019')
+ '\nparseInt(\'019\', 10): ' + parseInt('019', 10)
);
Whether '+' is better depends on the metric - it may be faster (I doubt
you'll notice either way), it's certainly fewer keystrokes and you
don't need to deal with the radix issue. parseInt() might be more
obvious for maintenance.
--
Rob

Aug 10 '06 #6
JRS: In article <11**********************@p79g2000cwp.googlegroups .com>
, dated Wed, 9 Aug 2006 18:22:15 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auposted :
>The "+" operator is overloaded, it can mean (amongst other things)
arithmetic addition or string concatenation. Variables in JavaScript
aren't typed,
Better I think to say "Identifiers"; Javascript variables contain a type
indication at run-time, whereas Pascal ones do not, but their type is
known at compile time.
so in order to work out how to apply the "+" operator in
a given situation the script engine looks at the values of the
variables that the "+" operator is applied to. It works from left to
right evaluating the result as it goes. If any variable is a string,
concatenation is inferred from that point on and a string is returned,
even if the remaining variables are numbers.
Except for the effects of unary +, which numberises its argument; and
the effects of parentheses - "Fred" + (1+2) is Fred3 not Fred12.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Delphi 3 Turnpike 4 ©
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.bancoems.com/CompLangPascalDelphiMisc-MiniFAQ.htmclpdmFAQ;
<URL:http://www.borland.com/newsgroups/guide.htmlnews:borland.* Guidelines
Aug 10 '06 #7
JRS: In article <11*********************@m73g2000cwd.googlegroups. com>,
dated Thu, 10 Aug 2006 04:00:35 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auposted :
>
Whether '+' is better depends on the metric - it may be faster (I doubt
you'll notice either way), it's certainly fewer keystrokes and you
don't need to deal with the radix issue. parseInt() might be more
obvious for maintenance.
Unary + is believed to be fastest in execution.
Bur parseInt(S, 10) happily ignores trailing non-digits, which is useful
in reading such as "14px".

If S is "1e6", parseInt(S) < parseFloat(S)

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
I find MiniTrue useful for viewing/searching/altering files, at a DOS prompt;
free, DOS/Win/UNIX, <URL:http://www.idiotsdelight.net/minitrue/>
Aug 10 '06 #8
Dr John Stockton <jr*@merlyn.demon.co.ukwrites:
JRS: In article <11**********************@p79g2000cwp.googlegroups .com>
, dated Wed, 9 Aug 2006 18:22:15 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auposted :
>>The "+" operator is overloaded, it can mean (amongst other things)
arithmetic addition or string concatenation. Variables in JavaScript
aren't typed,

Better I think to say "Identifiers";
I would use "identifier" about the variable's name. A variable is
something whose value can change, and it has a name for reference.
Javascript variables contain a type indication at run-time, whereas
Pascal ones do not, but their type is known at compile time.
Javascript variables has no type, at compile or run-time, but the
value the variable is bound to at any given time does.
>so in order to work out how to apply the "+" operator in
a given situation the script engine looks at the values of the
variables that the "+" operator is applied to. It works from left to
right evaluating the result as it goes. If any variable is a string,
concatenation is inferred from that point on and a string is returned,
even if the remaining variables are numbers.

Except for the effects of unary +, which numberises its argument; and
the effects of parentheses - "Fred" + (1+2) is Fred3 not Fred12.
Indeed, the behavior of the binary plus operator depends on the types
of its operands. What those operands are is determined the usualy way,
using associativity and precedence of other operators in the
expression, including parentheses. The associativity of operators is
often left to right.

In the example above, the operands of the second plus is 1 and 2, both
numbers, so the result is 3. The operands of the first plus is the
string "Fred" and the number 3, so the result is "Fred3".

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 10 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: John Wilkinson | last post by:
Hi, I am new to XSLT. My problem is that I wish to create an HTML table, and give each row an incrementing number from 1.This would increment every itteration of a for-each loop. The XSLT...
2
by: brian | last post by:
Hi, before coming to .NET, I utilized regular expressions mostly in JScript / JavaScript and also in my favorite text editor: TextPad (www.textpad.com) I don't know about JScript/JavaScript, but...
10
by: Antanas | last post by:
The problem is that when AddID is used multiple times in the same select statement, it returns the same value in all places. How could I force function AddID to increment OBJECTID sequence? Here...
26
by: Bas Wassink | last post by:
Hi there, Does the ANSI standard say anything about incrementing variables past their limits ? When I compile code like this: unsigned char x = 255; x++; printf ( "%d\n", x );
27
by: Erik de Castro Lopo | last post by:
Hi all, The GNU C compiler allows a void pointer to be incremented and the behaviour is equivalent to incrementing a char pointer. Is this legal C99 or is this a GNU C extention? Thanks in...
10
by: pozz | last post by:
Hi all, I need to write a simple incrementing/decrementing function like this: unsigned char change( unsigned char x, unsigned char min, unsigned char max, signed char d); x is the value...
53
by: subramanian100in | last post by:
I saw this question from www.brainbench.com void *ptr; myStruct myArray; ptr = myArray; Which of the following is the correct way to increment the variable "ptr"? Choice 1 ptr = ptr +...
7
by: jwhitby3 | last post by:
Hi all, I am trying to develop what amounts to a data entry page for the company I work for, (mostly to make my job easier). I think that I am beginning to grasp php, but I am at a loss now. I...
3
by: Elementary | last post by:
I have a number of variables, e.g. X1, X2, X3, X4, X5. I want to select only the ones that are non zero(there will only be 2 or 3 at any time), and record them as Y1, Y2 and Y3 I want to know...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.