469,353 Members | 2,053 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,353 developers. It's quick & easy.

Check null or 0

I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.

Regards,

S

Feb 27 '06 #1
18 4492
sta...@gmail.com wrote:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.

Regards,

S


try this:

forecast = forecast + parseInt(f[i].value);

http://www.w3schools.com/jsref/jsref_parseInt.asp

- JS

Feb 27 '06 #2

st****@gmail.com wrote:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);


The use of eval is most often misused and unnecessary.

Try the following to create your sum:

forecast += +f[i].value;

Feb 27 '06 #3
wrote on 27 feb 2006 in comp.lang.javascript:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.


eval() is evil, and I see no reason why you are using it here.

===========

If you mean the following:

var forecast = 7
var xxx = 8
var yyy ='xxx'
forecast = forecast + eval(yyy);
alert(forecast) //15

it is much better to use:

var forecast = 7
var xxx = 8
var yyy ='xxx'
forecast = forecast + window[yyy];
alert(forecast) //15

now what if xxx is not initialized or NaN:

var forecast = 7
var xxx
var yyy = 'xxx'
if (!window[yyy]||isNaN(window[yyy])) {
var a = 0
yyy = 'a'
}
forecast = forecast + window[yyy];
alert(forecast) //7

will this help?
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Feb 27 '06 #4
st****@gmail.com wrote:
I'm using the following code to create a sum:
forecast = forecast + eval(f[i].value);
Don't use eval.
http://www.JavascriptToolbox.com/bestpractices/
This only works if "f[i].value" contains a number.
Can someone please help me so that it also works if "f[i].value" is
empty or contains text.


Well, what do you want it to do?
Should it treat non-number values as 0?
Ignore them?
Throw up an error?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Feb 27 '06 #5
st****@gmail.com said the following on 2/27/2006 1:30 PM:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.


Simple. Drop the eval:

forecast = forecast + f[i].value;

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 28 '06 #6
VK

st****@gmail.com wrote:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.


forecast += +(f[i].value)||0;

P.S. I decided to participate in the squeezcrypt rally :-) I did not
play squeezcrypt for rather long so just cheking my fingers are stll
flexible :-)

The decrypter version (if someone curious) is:

var n = parseInt(f[i].value, 10);
if (isNaN(n)) {
forecast += 0;
}
else {
forecast += n;
}

Feb 28 '06 #7
VK wrote:
forecast += +(f[i].value)||0;
There's no need for the parenthesis.
P.S. I decided to participate in the squeezcrypt rally :-) I did not
play squeezcrypt for rather long so just cheking my fingers are stll
flexible :-) [...] The decrypter version (if someone curious) is:


I saw a lot of people criticizing you here, I thought they just hated
you, but after reading this message I can see they are totally right
hahaha ;]
--
Jonas Raoni Soares Silva
http://www.jsfromhell.com
Feb 28 '06 #8
VK

Jonas Raoni wrote:
VK wrote:
forecast += +(f[i].value)||0;
There's no need for the parenthesis.


Right.

forecast+=+f[i].value||0;

As I said I did not play squeezcrypt for a while :-)

I saw a lot of people criticizing you here, I thought they just hated
you, but after reading this message I can see they are totally right
hahaha ;]


Oh boy, did we get hurt? :-( ;-)
I thought there were enough of smilies in my post to prevent that -
plus nothing personal.

So what the exact reason of *your* hate is? That I explained what did
forecast+=+f[i].value||0;
do and mean?

It's hard to believe, I know, but it is not so obvious at all to an
average user. Plus some people may prefer to use the conventional
isNaN() check so I thought necessary to mention it.

Feb 28 '06 #9
VK wrote:
Jonas Raoni wrote:
I saw a lot of people criticizing you here, I thought they just hated
you, but after reading this message I can see they are totally right
hahaha ;]
Oh boy, did we get hurt? :-( ;-)


Hahahaha, no! We'll never get hurt, this isn't an arena, but a place to
spend some free time, I don't take anything personally ;]

Even disliking such unuseful discussions, I can't resist to my agressive
instinct, so if you can, stop this thread by not answering, it's already
over, the question got an answer =]
So what the exact reason of *your* hate is? That I explained what did
forecast+=+f[i].value||0;
do and mean?
Yeah, that's the reason, explaining how the script works looks idiot for
me, I explain only if the person asks for explanation.
It's hard to believe, I know, but it is not so obvious at all to an
average user. Plus some people may prefer to use the conventional
isNaN() check so I thought necessary to mention it.


You're right, but explaining the script is a kind of insult for the
idiot people like me haha. I assume everybody has a nice knowledge about
the language, so nothing needs explanation.
--
Jonas Raoni Soares Silva
http://www.jsfromhell.com
Feb 28 '06 #10
Jonas Raoni wrote:
VK wrote:
forecast += +(f[i].value)||0;
There's no need for the parenthesis.
P.S. I decided to participate in the squeezcrypt rally :-)
I did not play squeezcrypt for rather long so just cheking
my fingers are stll flexible :-)

[...]
The decrypter version (if someone curious) is:


I saw a lot of people criticizing you here,
I thought they just hated you,


It isn't hatred, it isn't even personal. VK posts absolute rubbish to
the group; fictional explanations, worst possible advice and error
filled/catastrophically poor code that he doesn't even understand
himself. He will be corrected and criticised for doing that, anyone
would. However, the tone of those criticisms has changed over time
because no matter how much effort you put into correcting, explaining
and demonstrating why he is mistaken he refuses to believe anything that
originates outside of his own head and caries on re-posting repetitions
of the same rubbish again and again.

The effect of this is doubly bad for the group as individuals suffer
from his advice and others have to expend effort futilely correcting his
nonsense, preventing them form rendering a direct service to others (due
the limited availability of time).
but after reading this message I can see they are totally
right hahaha ;]


Yes, although VK believes himself to be the ultimate arbiter of
javascript knowledge he doesn't actually know that his "decrypter"
version does not do the same as the first version. It is a knowledge
shortfall that he cannot see for himself as that would mean recognising
that his arrogant self-confidence in what he believes to be his own
superior understanding of javascript is fictitious.

Richard.
Mar 1 '06 #11
JRS: In article <8c********************@comcast.com>, dated Mon, 27 Feb
2006 20:40:34 remote, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
st****@gmail.com said the following on 2/27/2006 1:30 PM:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.


Simple. Drop the eval:

forecast = forecast + f[i].value;


Generally, a .value is a string. Your code will then concatenate, even
if the string is numeric.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Mar 1 '06 #12
Dr John Stockton said the following on 3/1/2006 12:41 PM:
JRS: In article <8c********************@comcast.com>, dated Mon, 27 Feb
2006 20:40:34 remote, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
st****@gmail.com said the following on 2/27/2006 1:30 PM:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text. Simple. Drop the eval:

forecast = forecast + f[i].value;


Generally, a .value is a string.


The value of a form element is always a string. And the code implies
form elements but it could just as well be an array in which case the
..value is not needed and can be counter-productive.
Your code will then concatenate, even if the string is numeric.


You don't say? Well guess what Doc, that is what the OP asked for!

Let me quote part of the original post that you, and everybody else,
that replied seemed to miss:

<quote>
Can someone please help me so that it also works if "f[i].value" is
empty or contains text.
</quote>

The *only* way to "add" text is to concatenate. And everybody else,
especially you, got caught up in converting strings to numbers and
didn't bother to read the post thoroughly. Had you done so, and not been
in such a haste to correct me in particular, you wouldn't even have
posted a reply to me.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 2 '06 #13
Randy Webb wrote:
Dr John Stockton said the following on 3/1/2006 12:41 PM:
JRS: In article <8c********************@comcast.com>, dated Mon, 27 Feb
2006 20:40:34 remote, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
st****@gmail.com said the following on 2/27/2006 1:30 PM:

I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.

Simple. Drop the eval:

forecast = forecast + f[i].value;

Generally, a .value is a string.

The value of a form element is always a string. And the code implies
form elements but it could just as well be an array in which case the
.value is not needed and can be counter-productive.
Your code will then concatenate, even if the string is numeric.

You don't say? Well guess what Doc, that is what the OP asked for!

Let me quote part of the original post that you, and everybody else,
that replied seemed to miss:

<quote>
Can someone please help me so that it also works if "f[i].value" is
empty or contains text.
</quote>


I think the real problem is that the OP never stipulated any criteria
for 'works'. Yours is one possible interpretation, there are others.
The OP's statement that:

"I'm using the following code to create a sum:"
might be taken as a hint that arithmetic addition was required.

The use of eval is another hint as its effect on a string consisting
solely of digits is to convert it to a type number, but if the string
contains any other characters it will return an error.

It is understandable that you discounted that when interpreting the OP's
intentions as the consequences of eval's use are almost never understood
by those who post examples of it here (i.e. the OP didn't understand the
consequences, I'm certain that you do).
To the OP, if lurking:

eval will convert a number that is a string to a JavaScript 'primitive'
number, e.g.

var x = '5'; // the value of x is type string
x = eval(x); // the value of x is now type number
However:

var x = '5px';
x = eval(x); // Error: missing ; before statement
eval is a black box, the error messages emanating from it are usually
bizarre and useless for debugging. It has other unwelcome consequences
(search the archives) - just don't use eval.

Other posts in this thread have offered good solutions.
[...]

--
Rob
Mar 2 '06 #14
RobG said the following on 3/1/2006 8:19 PM:
Randy Webb wrote:
Dr John Stockton said the following on 3/1/2006 12:41 PM:
JRS: In article <8c********************@comcast.com>, dated Mon, 27 Feb
2006 20:40:34 remote, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :

st****@gmail.com said the following on 2/27/2006 1:30 PM:

> I'm using the following code to create a sum:
>
> forecast = forecast + eval(f[i].value);
>
> This only works if "f[i].value" contains a number.
>
> Can someone please help me so that it also works if "f[i].value" is
> empty or contains text.

Simple. Drop the eval:

forecast = forecast + f[i].value;
Generally, a .value is a string.

The value of a form element is always a string. And the code implies
form elements but it could just as well be an array in which case the
.value is not needed and can be counter-productive.
Your code will then concatenate, even if the string is numeric.

You don't say? Well guess what Doc, that is what the OP asked for!

Let me quote part of the original post that you, and everybody else,
that replied seemed to miss:

<quote>
Can someone please help me so that it also works if "f[i].value" is
empty or contains text.
</quote>


I think the real problem is that the OP never stipulated any criteria
for 'works'. Yours is one possible interpretation, there are others.


Yes, and given the entirety of the post, I made my interpretation.
Rather than seeing the differences in interpretations, John does as John
typically does and tries to be pedantic. John can go Fornicate Under
Consent of King with himself for all I care :)
The OP's statement that:

"I'm using the following code to create a sum:"
might be taken as a hint that arithmetic addition was required.
It could also be taken as a hint that concatenation is being
used/desired as in "adding things together" in the sense of strings.
The use of eval is another hint as its effect on a string consisting
solely of digits is to convert it to a type number, but if the string
contains any other characters it will return an error.
eval's use is typically nothing more than a hint of the ignorance of the
person using it. Nothing more, nothing less.
It is understandable that you discounted that when interpreting the OP's
intentions as the consequences of eval's use are almost never understood
by those who post examples of it here (i.e. the OP didn't understand the
consequences, I'm certain that you do).
Precisely. And given the ambiguity of "a sum", the context of "I want it
to work if it contains text" leaves me to assume its string
concatenation and dropping the use of eval from the original code does
precisely that.

To the OP, if lurking:

eval will convert a number that is a string to a JavaScript 'primitive'
number, e.g.

var x = '5'; // the value of x is type string
x = eval(x); // the value of x is now type number

However:

var x = '5px';
x = eval(x); // Error: missing ; before statement
Which browser? None of mine throw any error at all, nothing:

IE6, Firefox, Mozilla, and Opera 7/8/9

But, adding an alert before and after the eval call does some odd
things. All give the initial alert (naturally) but none of them give the
second alert:

var x = "5px";
alert(x);
x = eval (x);
alert(x);

eval is a black box, the error messages emanating from it are usually
bizarre and useless for debugging. It has other unwelcome consequences
(search the archives) - just don't use eval.
If you get the error messages at all :-\
Other posts in this thread have offered good solutions.


Only if its addition and not string concatenation that is wanted :-)
--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 2 '06 #15
Randy Webb wrote:
RobG said the following on 3/1/2006 8:19 PM: [...]
However:

var x = '5px';
x = eval(x); // Error: missing ; before statement

Which browser? None of mine throw any error at all, nothing:

IE6, Firefox, Mozilla, and Opera 7/8/9


For me, Firefox 1.5.0.1 and IE: 6.0.2800.1106.xpsp2.050301-1526
(amazingly the IE error is pretty similar to the Firefox error).

The error string posted is copied directly from Firefox's JavaScript
console. IE shows an error the first time the page is loaded, using
re-load makes it go away.

But, adding an alert before and after the eval call does some odd
things. All give the initial alert (naturally) but none of them give the
second alert:

var x = "5px";
alert(x);
x = eval (x);
alert(x);


Because of the error I guess - why you don't see it is a mystery. :-(

eval is a black box, the error messages emanating from it are usually
bizarre and useless for debugging. It has other unwelcome consequences
(search the archives) - just don't use eval.

If you get the error messages at all :-\
Other posts in this thread have offered good solutions.

Only if its addition and not string concatenation that is wanted :-)


I thought your post covered that. ;-)

--
Rob
Mar 2 '06 #16
RobG wrote:
eval will convert a number that is a string to a JavaScript 'primitive'
number, e.g.

var x = '5'; // the value of x is type string
x = eval(x); // the value of x is now type number
However, there are occasions where eval() returns `undefined' even though
the passed expression would evaluate to a different value.
However:

var x = '5px';
x = eval(x); // Error: missing ; before statement
eval is a black box, the error messages emanating from it are usually
bizarre ^^^^^^^
That is, if I may say so, VK-ish wording ;-) The error message above, for
example, is not bizarre at all if you understand the language, and how its
tokenizer works (all described in the ECMAScript specifications). AIUI, 5
is considered a NumericLiteral because only `px' is what qualifies as an
Identifier here (which MUST NOT start with a decimal digit according to the
specs), and is therefore considered the statement (produced by `Statement
--> ... --> PrimaryExpression : Identifier'). `5;px', as indicated by the
error message, would not make much sense and could even qualify as being
bizarre, but it is _syntactically correct_; `5px' is _not_.
and useless for debugging.
Quite the contrary. eval() can be used for debugging in combination with
the proprietary `onerror' handler when exception handling with try...catch
is not available. Venkman, and the MS Script Debugger can debug eval()
code quite well.
It has other unwelcome consequences (search the archives) - just don't
use eval.


.... if you can avoid it. As you can (and should) here, by using

x = parseInt(x, 10); // or parseFloat(...)

instead. Which is an appropriate, but still not sufficient answer to
the OP's request "that it also works if 'f[i].value' is empty or contains
text." Because NaN to which (the more efficient, but not fully backwards
compatible) `+f[i].value' evaluates then is hardly useful.
PointedEars
Mar 2 '06 #17
Thomas 'PointedEars' Lahn wrote:
RobG wrote:

eval will convert a number that is a string to a JavaScript 'primitive'
number, e.g.

var x = '5'; // the value of x is type string
x = eval(x); // the value of x is now type number

However, there are occasions where eval() returns `undefined' even though
the passed expression would evaluate to a different value.


The point is that although eval() 'works' for the OP in one particular
case, it has unwanted results in others. When the above is taken in
context with the paragraphs that followed, your statement is in
accordance with that - rather than 'however', you could have used 'and
also...'.

However:

var x = '5px';
x = eval(x); // Error: missing ; before statement
eval is a black box, the error messages emanating from it are usually
bizarre


^^^^^^^
That is, if I may say so, VK-ish wording ;-)


Eeek! :-o

The error message above, for
example, is not bizarre at all if you understand the language,


Working backwards to create an explanation of the outcome is called
'20/20 hindsight'. It is being able to work forward and say with
certainty what the outcome *will* be that counts.

This statement seems at odds with the the one further up:

"there are occasions where eval() returns `undefined' even
though the passed expression would evaluate to a different
value."

which seems to agree with my characterisation - although 'bizarre' might
have been a bit strong. :-)
[...]
and useless for debugging.

Quite the contrary. eval() can be used for debugging in combination with
the proprietary `onerror' handler when exception handling with try...catch
is not available.


I was talking about debugging code that includes the use of eval, not
that eval is completely useless for debugging.
[...]
--
Rob
Mar 2 '06 #18
JRS: In article <Wr********************@comcast.com>, dated Wed, 1 Mar
2006 19:42:42 remote, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
Dr John Stockton said the following on 3/1/2006 12:41 PM:
JRS: In article <8c********************@comcast.com>, dated Mon, 27 Feb
2006 20:40:34 remote, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
st****@gmail.com said the following on 2/27/2006 1:30 PM:
I'm using the following code to create a sum:

forecast = forecast + eval(f[i].value);

This only works if "f[i].value" contains a number.

Can someone please help me so that it also works if "f[i].value" is
empty or contains text.
Simple. Drop the eval:

forecast = forecast + f[i].value;
Generally, a .value is a string.


The value of a form element is always a string.


Agreed that the .value is a string, though a drop-down list might be
said to have a selected value. But a .value is not necessarily a form
element; hence the "Generally,".
And the code implies
form elements
Not inevitably. Probably, though, the OP does want to sum the values of
form elements.. But, in writing "Generally, a .value is a string.", I
was of course referring to the generality of .value, not just what the
OP probably had in mind. Have you considered attending an EFL course?

but it could just as well be an array in which case the
.value is not needed and can be counter-productive.
Your code will then concatenate, even if the string is numeric.
You don't say? Well guess what Doc, that is what the OP asked for!


He asked explicitly for a sum. Summation is not concatenation.
Let me quote part of the original post that you, and everybody else,
that replied seemed to miss:

<quote>
Can someone please help me so that it also works if "f[i].value" is
empty or contains text.
</quote>

The *only* way to "add" text is to concatenate.
No, he might want non-numeric text to count as zero. Also, "contains
text" applies not only to "cat" but to "99dog", in which case
interpretation as +99 seems probably wanted (and parseInt(,) can be
used). It also applies to "Price $99" in which case one might prefer to
extract the digits with a RegExp.
And everybody else,
especially you, got caught up in converting strings to numbers and
didn't bother to read the post thoroughly. Had you done so, and not been
in such a haste to correct me in particular, you wouldn't even have
posted a reply to me.


When I read it, I saw, and understood, the word "sum". YWII, RBTD.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
Mar 3 '06 #19

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Martin | last post: by
3 posts views Thread by GS | last post: by
1 post views Thread by shapper | last post: by
3 posts views Thread by Helen Wheels | last post: by
14 posts views Thread by Mark | last post: by
1 post views Thread by CARIGAR | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.