Anybody who does any programming will/should have heard of the "with" statement. I don't know why but I had always assumed this wasn't available in JavaScript. That was until today when I typed it in to Dreamweaver and it turned blue, signifying it as being a keyword.
After a bit of playing around working out what syntax it expected I came up with a solution that will help symplify most JavaScripts that I write.
Imagine we want to validate a form with four fields on it, called "Text1", "Text2", Text3" and "Text4". We could write a function like this:
function validateFields(){Nothing wrong with this script, per se. It is a bit heavy on the old fingers though. We could simplify it in to the following function.
if (document.forms[0].Text1.value == ""){
alert("You need to enter a value for Text1");
document.forms[0].Text1.focus( );
return false;
}
if (document.forms[0].Text2.value == ""){
alert("You need to enter a value for Text2");
document.forms[0].Text2.focus();
return false;
}
if (document.forms[0].Text3.value == ""){
alert("You need to enter a value for Text3");
document.forms[0].Text1.focus();
return false;
}
if (document.forms[0].Text4.value == ""){
alert("You need to enter a value for Text4");
document.forms[0].Text4.focus();
return false;
}
}
function validateFields(){This one is a little easier on the keyboard. But not as much as this next one, which uses the with statement:
var frm = document.forms[0];
if (frm.Text1.value == ""){
alert("You need to enter a value for Text1");
frm.Text1.focus();
return false;
}
if (frm.Text2.value == ""){
alert("You need to enter a value for Text2");
frm.Text2.focus();
return false;
}
if (frm.Text3.value == ""){
alert("You need to enter a value for Text3");
frm.Text3.focus();
return false;
}
if (frm.Text4.value == ""){
alert("You need to enter a value for Text4");
frm.Text4.focus();
return false;
}
}
function validateFields(){And finally an example form that uses the above script.
with (document.forms[0]) {
if (Text1.value == ""){
alert("You need to enter a value for Text1");
Text1.focus();
return false;
}
if (Text2.value == ""){
alert("You need to enter a value for Text2");
Text2.focus();
return false;
}
if (Text3.value == ""){
alert("You need to enter a value for Text3");
Text3.focus();
return false;
}
if (Text4.value == ""){
alert("You need to enter a value for Text4");
Text4.focus();
return false;
}
}
alert("All fields are OK!");
}
Copyright © 2000 - 2024 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net