webmaster Posted April 25, 2009 Share Posted April 25, 2009 What exactly does the with() statement do? I have seen it mentioned on a couple of examples, but i don't see an explanation for it anywhere on w3schools. Can someone explain this to me? Link to comment Share on other sites More sharing options...
jeffman Posted April 25, 2009 Share Posted April 25, 2009 with is a shortcut for accessing the members of an object (including arrays) without naming the object. It is especially useful when you want to access a lot of members, since it cuts down on typing and makes the code more readable. Example: my_object = {}; my_object.name = "Cindy"; my_object.color = "blond"; my_object.job = "florist"; my_object.age = 24; with (my_object) { str = name + " the " + color + " " + job + " is " + age; alert (str); } If I hadn't used with, the string assignment line would have to look like this: str = my_object.name + " the " + my_object.color + " " + my_object.job + " is " + my_object.age; Link to comment Share on other sites More sharing options...
Guest FirefoxRocks Posted April 25, 2009 Share Posted April 25, 2009 Does with() also work with PHP? Link to comment Share on other sites More sharing options...
jeffman Posted April 25, 2009 Share Posted April 25, 2009 Does with() also work with PHP?Naah. But I never use it in Javascript anyway. If there's an advantage to it, besides smaller code, I don't see it. Link to comment Share on other sites More sharing options...
webmaster Posted April 26, 2009 Author Share Posted April 26, 2009 So with this example: <html><head><script type="text/javascript">function validate_required(field,alerttxt){with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } }}function validate_form(thisform){with (thisform) { if (validate_required(email,"Email must be filled out!")==false) {email.focus();return false;} }}</script></head><body><form action="submit.htm" onsubmit="return validate_form(this)" method="post">Email: <input type="text" name="email" size="30"><input type="submit" value="Submit"></form></body></html> , there really is no object, and there is an if statement within with. Can someone explain to me why the with() statement is used here? Link to comment Share on other sites More sharing options...
Ingolme Posted April 26, 2009 Share Posted April 26, 2009 "thisform" becomes a form object containing all the input elements inside it. Link to comment Share on other sites More sharing options...
justsomeguy Posted April 27, 2009 Share Posted April 27, 2009 If Javascript finds an undefined variable inside a with block, it will check to see if the object contains a property with the same name. The first if statement checks a variable called value, if there's no defined variable called value then it looks for field.value instead. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.