Ahhh...that did it.

As MorningZ mentioned, it was a misunderstanding of the scoping of the
variable:
inside vs outside the function.  I thought, too, being a "learn as I code"
programmer,
that anytime I defined a variable, I needed to precede it with "var"...
live and learn...or rather, code and learn...

Thanks, James and MZ...

-----Original Message-----
From: jquery-en@googlegroups.com [mailto:jquery...@googlegroups.com] On
Behalf Of James
Sent: Wednesday, September 02, 2009 10:45 PM
To: jQuery (English)
Subject: [jQuery] Re: Why is console.log(valid) returning "yes" in this
code?


I think you mean:
by using that, you are -NOT- stomping over the "outside" one.

Rick,

If you don't understand, using "var" is a variable declaration.
Setting: var valid = 'no';
inside the each() callback function will have that variable exist
locally only inside that function. It will not overwrite what you have
set globally.
Since you're doing the console.log outside of that function, it'll use
the one you set in the global scope,
var valid = 'yes';

To fix that, remove the "var" in: var valid = 'no';


On Sep 2, 4:36 pm, MorningZ <morni...@gmail.com> wrote:
> "Why?"
>
> Because you are failing to understand "variable scope"
>
> Don't use the "var" keyword inside the if block, by using that, you
> are stomping over the "outside" one
>
> http://www.google.com/search?q=Javascript+variable+scope
>
> On Sep 2, 10:26 pm, "Rick Faircloth" <r...@whitestonemedia.com> wrote:
>
> > Here's the code:
>
> > var valid = 'yes';
>
> > $(':input').each(function() {
>
> >    if   (   $(this).val().length == 0   )
>
> >         {   alert('in!');
>
> >             var valid = 'no';
>
> >             alert(valid);
>
> >             $('#rentalAppErrors').fadeIn(500);
>
> >             $(this).addClass('inputError');
>
> >             $(this).css({'background-color':'red','color':'#fff'});
>
> >             $(this).val('Entry required...');                         }
>
> > });
>
> > console.log(valid);
>
> > When I run this code making the "if" statement true, I get the
alert('in!')
> > properly,
>
> > letting me know that I'm inside the conditional block.  I also get the
> > second
>
> > alert, alert(valid), and the value of "valid" in the alert is "no".as it
> > should be.
>
> > But when the code gets to the console.log(valid) function, valid shows
in
> > the console
>
> > as having the value 'yes'.
>
> > ???
>
> > Why?  This is throwing the rest of my code off.
>
> > Rick
>
> >
----------------------------------------------------------------------------
> > ---------------------------------------
>
> > "Those who hammer their guns into plows will plow for those who do not."
 -
> > Thomas Jefferson
>
>


Reply via email to