...

View Full Version : Exiting a .each in json



marshallw
04-05-2009, 12:51 AM
Hello,

Perhaps this is a trivial problem, but I've been searching for quite a while with no success, so I thought I'd ask here.

In a piece of code of mine, I loop through an array containing the names of several fields on my web page using .each. If any fields are empty, I want it to pop up a message displaying that that field is empty and exit exit the javascript function, but all my attempts are failing. Instead it goes through every object in the array, so it'll popup "auctionID is empty", "password is empty", etc. I tried return;, return 1;, exit, break, etc. (json is relatively new to me, so I'm still learning what's what in it.)

Anyways, here's some code:



Event.observe("Login", "submit",
function(event)
{
aTextFields = new Array("auctionID", "password");

aTextFields.each(
function(elem, pos)
{
if (Form.Element.checkForEmpty(elem, $F(elem)))
{
Event.stop(event);
return false;
}
})
});

/****************
* Extend Form.Element with checkForEmpty
* Purpose: checks the fields, and if they're empty tell the users which ones.
****************/
Object.extend(Form.Element,
{
checkForEmpty: function(elem, value)
{
if (value.length == 0)
{
alert("Element " + elem + " is empty ");
$(elem).focus();
return true;
}
return false;
}
});


I wrote this a while back so I'm not as familiar with it as I once way, but it feels like Event.stop(event) should be what prevents the code from continuing from running. Once again if someone could help me, I'd be very grateful. Thanks!

rnd me
04-05-2009, 01:34 AM
there's no way to stop .each early.

you can use a for loop instead, and the break or return can get you out early...

marshallw
04-05-2009, 10:32 PM
hmm, too bad. I thought of a quick little hack to get by this: declaring a boolean, and if it enters the if loop set to false. only enter the if loop if the boolean is true. This seems to work.

Thanks for the information.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum