Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

JavaScript Forum


You are currently viewing our JavaScript Forum as a guest. Please register to participate.
Login



Reply
jQuery equivalent of a for loop
Old 03-17-2010, 01:03 PM jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
I have the following code that I'm using to cycle through each element in a form field, and clear whatever text is in it. If the user clicks out of the field without typing anything then the script is supposed to return to whatever value it started with (e.g. "Enter your name..."). If the user does type something, then it stays in the field even when they click out of it:
Code:
// clear the text in the form fields

$(document).ready(function() {
    $('#frm-quick input').focus(function() {
        var fieldFocus = 0;
        var fieldVal = $(this).val();
            if (fieldFocus == 0) {
                $(this).val('');
            }
            $(this).keydown(function() {
                fieldFocus = 1;
            })
        })
        $(this).blur(function() {
            if (fieldFocus == 0) {
                $(this).val(fieldVal);
            }
    })
})
I can see that fieldVal and fieldFocus will be overwritten each time the loop does a cycle. Meaning their values will be meaningless.

What I want to do is use an array. I know how to do this in traditional JavaScript no problem (e.g. something like fieldVal[i] = ...), but how would I do it in jQuery?? As the loop seems to be 'automatic'.
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
 
Register now for full access!
Old 03-17-2010, 02:15 PM Re: jQuery equivalent of a for loop
wayfarer07's Avatar
Poo on You

Latest Blog Post:
Introducing WowWindow
Posts: 3,987
Name: Abel Mohler
Location: Asheville, North Carolina USA
Trades: 0
jQuery has the "each" method which can be used to loop over any DOM element:
Code:
$('form *').each(function() {
    alert(this.nodeName);
});
The value of "this" inside the anonymous function passed to jQuery.each is the DOM node we're looping over.
__________________
I build web things. I work for the startup
Please login or register to view this content. Registration is FREE
.
wayfarer07 is offline
Reply With Quote
View Public Profile Visit wayfarer07's homepage!
 
Old 03-24-2010, 02:45 PM Re: jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
Ahhhh, thanks!
How would I add values to an array in the each method?

like the equivalent of using 'someVariable[i] = $(this).val' if that makes sense?
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
Old 03-24-2010, 05:47 PM Re: jQuery equivalent of a for loop
wayfarer07's Avatar
Poo on You

Latest Blog Post:
Introducing WowWindow
Posts: 3,987
Name: Abel Mohler
Location: Asheville, North Carolina USA
Trades: 0
The most elegant way would be to use the Array push() method. This is native to JavaScript and has nothing to do with jQuery: array.push() adds a value to the end of the array.

Code:
var someVariable = [];
$('form *').each(function() {
    someVariable.push($(this).val());
});
Note that jQuery's val() method is expressed $(this).val(), not $(this).val; It is a function, or method, that returns the value attribute, not a property.
__________________
I build web things. I work for the startup
Please login or register to view this content. Registration is FREE
.
wayfarer07 is offline
Reply With Quote
View Public Profile Visit wayfarer07's homepage!
 
Old 03-25-2010, 06:30 AM Re: jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
Ok thanks I'll give it a try!
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
Old 03-25-2010, 12:55 PM Re: jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
Another problem! I keep getting errors saying that 'fieldVal' is undefined. I assume it's because it's outside of the function, but I thought declaring a variable with the 'var' statement made it global?

Here is my code so far:
Code:
$(document).ready(function() {
    var fieldVal;
    $('#frm-quick *').each(function() {
        var fieldFocus = 0;
        fieldVal.push = $(this).val();
            if (fieldFocus == 0) {
                $(this).val('');
            }
            $(this).keydown(function() {
                fieldFocus = 1;
            })
        })
        $(this).blur(function() {
            if (fieldFocus == 0) {
                $(this).val(fieldVal);
            }
    })
})
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
Old 03-25-2010, 05:56 PM Re: jQuery equivalent of a for loop
chrishirst's Avatar
Missing! presumed drunk.

Posts: 42,383
Name: Chris Hirst
Location: Blackpool. UK
Trades: 0
'Tother way round.

A variable declared and intialised inside a function WITHOUT var it will be global in scope.
With var it will be local
__________________
Chris. ->>
Please login or register to view this content. Registration is FREE
<<-

A foolish consistency is the hobgoblin of little minds
Thought for today:- Is SEO the only industry where all the cowboys are Indians?
chrishirst is online now
Reply With Quote
View Public Profile Visit chrishirst's homepage!
 
Old 03-25-2010, 07:57 PM Re: jQuery equivalent of a for loop
wayfarer07's Avatar
Poo on You

Latest Blog Post:
Introducing WowWindow
Posts: 3,987
Name: Abel Mohler
Location: Asheville, North Carolina USA
Trades: 0
Actually, the problem is just that this:
Code:
var fieldVal;
should be this:
Code:
var fieldVal = [];
And this:
Code:
fieldVal.push = $(this).val();
should be this:
Code:
fieldVal.push($(this).val());
.push is a method, so it shouldn't take an assignment (.push = something). It is a function and is passed an argument. However it is only a method of an Array object, so fieldVal needs to be initialized in the enclosing scope either as [] or new Array()
__________________
I build web things. I work for the startup
Please login or register to view this content. Registration is FREE
.
wayfarer07 is offline
Reply With Quote
View Public Profile Visit wayfarer07's homepage!
 
Old 03-26-2010, 07:37 AM Re: jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
Thanks to both of you for clearing those things up. But now I have another problem!

Now that I'm using the 'push' method, I don't know how to refer to a specific part of the array.

e.g. the last instruction:
Code:
$(this).val(fieldVal);
Sets $(this) to the last value in the array. Is there a way of setting it to the appropriate value like in a traditional for loop (e.g. = fieldVal[i])

Code:
$(document).ready(function() {
    $('#frm-quick *').each(function() {
        fieldVal = [];
        fieldFocus = 0;
        fieldVal.push($(this).val());
        $(this).focus(function() {
            if (fieldFocus == 0) {
                $(this).val('');
            }
        })
        $(this).keydown(function() {
            fieldFocus = 1;
        })
        $(this).blur(function() {
            if (fieldFocus == 0) {
                $(this).val(fieldVal);
            }
        })
    })
})
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
Old 03-26-2010, 08:20 AM Re: jQuery equivalent of a for loop
wayfarer07's Avatar
Poo on You

Latest Blog Post:
Introducing WowWindow
Posts: 3,987
Name: Abel Mohler
Location: Asheville, North Carolina USA
Trades: 0
Just increment your own number inside the each function.
__________________
I build web things. I work for the startup
Please login or register to view this content. Registration is FREE
.
wayfarer07 is offline
Reply With Quote
View Public Profile Visit wayfarer07's homepage!
 
Old 03-26-2010, 12:01 PM Re: jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
Ahhh of course! That takes me back to my roots, when I was using while loops instead of for loops

Still seems to be a problem though! The line which reads:
Code:
$(this).val(fieldVal[count]);
If I explicitly set which instance of the array to use (Im probably not using the right terminoligy here) then it works. e.g. fieldVal[1] rather than using the 'count' variable then it works fine.

But if I used fieldVal[count] then it comes up as being undefined!

Code:
$(document).ready(function() {
    count = 0;
    fieldVal = [];
    fieldFocus = 0;
    $('#frm-quick input[type="text"], #frm-quick textarea').each(function() {
        fieldVal[count] = ($(this).val());
        $(this).focus(function() {
            if (fieldFocus == 0) {
                $(this).val('');
            }
        })
        $(this).keydown(function() {
            fieldFocus = 1;
        })
        $(this).blur(function() {
            if (fieldFocus == 0) {
                $(this).val(fieldVal[count]);
            }
        })
        count++;
    })
})
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
Old 03-26-2010, 12:40 PM Re: jQuery equivalent of a for loop
wayfarer07's Avatar
Poo on You

Latest Blog Post:
Introducing WowWindow
Posts: 3,987
Name: Abel Mohler
Location: Asheville, North Carolina USA
Trades: 0
Because by the time the event happens, count has been incremented to a point at which there is no value set in the array. When you reference count inside the blur event, it is using the non-local value of it, which has been incremented to the # of INPUT elements + 1.

Pass count to an anonymous closure so that it has its own local value when you bind the event:
Code:
(function(count){
    $(this).blur(function() {
        if (fieldFocus == 0) {
            $(this).val(fieldVal[count]);
        }
    })
})(count);
count++;
You might want to read this while you're at it:
How JavaScript Closures Work
__________________
I build web things. I work for the startup
Please login or register to view this content. Registration is FREE
.
wayfarer07 is offline
Reply With Quote
View Public Profile Visit wayfarer07's homepage!
 
Old 03-31-2010, 07:10 AM Re: jQuery equivalent of a for loop
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
Hmmm I've probably got this wrong, but is my code supposed to look like this?

Code:
$(document).ready(function() {
    count = 0;
    fieldVal = [];
    fieldFocus = 0;
    $('#frm-quick input[type="text"], #frm-quick textarea').each(function() {
        fieldVal[count] = ($(this).val());
        $(this).focus(function() {
            if (fieldFocus == 0) {
                $(this).val('');
            }
        })
        $(this).keydown(function() {
            fieldFocus = 1;
        })
        (function(count){
            $(this).blur(function() {
                if (fieldFocus == 0) {
                    $(this).val(fieldVal[count]);
                }
            })
        })(count);
        count++;
    })
})
As I am getting the error:
Quote:
Error: $(this).keydown(function () {fieldFocus = 1;}) is not a function
Source File: file:///Users/pealo86/Documents/design/resource/code/script/frm-field-clear.js
Line: 19
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
Old 03-31-2010, 08:17 AM Re: jQuery equivalent of a for loop
wayfarer07's Avatar
Poo on You

Latest Blog Post:
Introducing WowWindow
Posts: 3,987
Name: Abel Mohler
Location: Asheville, North Carolina USA
Trades: 0
No idea. Your syntax looks correct to me. If $(this).keydown isn't defined as a function, maybe your copy of jQuery is corrupted somehow.
__________________
I build web things. I work for the startup
Please login or register to view this content. Registration is FREE
.
wayfarer07 is offline
Reply With Quote
View Public Profile Visit wayfarer07's homepage!
 
Reply     « Reply to jQuery equivalent of a for loop
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.43440 seconds with 12 queries