PDA

View Full Version : Use of "with" statement.


vnmshenoy
02-05-2008, 08:16 AM
Hi guys,
This is my first post in this site....:)

I want to know the use of with statement.I read it in a book that we use it to save ourselves from typing....

example

frames[1].document.forms[0].address_field.value

can be written as
with(frames[1].document.forms[0])
{

name.value="";
address.value="";
etc..
}

Now see the code below...


<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)
{
alert("hello");
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==false)
{email.focus();return false;}
}
}
</script>
</head><body>
<form action="submitpage.htm"
onsubmit="return validate_form(this)"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body></html>



Above i want to know what i need to do to remove "with" clause.


if i replace it with below code

function validate_form(thisform)
{
alert("hello");

if (validate_required(email,"Email must be filled out!")==false)
{document.forms[0].email.focus();return false;}

}

i get an error which says

'email' is undefined.....


TELL ME HOW CAN I REMOVE WITH CLAUSE FROM HERE.....

rnd me
02-05-2008, 08:37 AM
if email is a prop of thisform, then code like below


function validate_form(thisform)
{
alert("hello");

if (validate_required(thisform.email,"Email must be filled out!")==false)
{document.forms[0].email.focus();return false;}
// alternate : {thisform.email.focus();return false;}

}

A1ien51
02-05-2008, 03:14 PM
From a perfomance aspect, with is not a good thing to use. The way it was written causes many many lookps. Thise lookups add up ater awhile. For a small porion of code where it is hit only one time, it is no big deal. If you use this in a major web app, you would notice the performance.

A better way to avoid typing a lot is to cache/store your object into a variable and reference it that way. It is very effiecient since there are no lookups for the object.

basic idea:

var form = document.formName;
form.myTextBox.value = "123";
form.mySelection.options.length = 0;
form = null;


Eric