2009-04-07

Object Detection of JavaScript

When you need to check the existence of the specific property or method of an object before you use it, you can use if statement like followings.

...
<script>
function iniPage(){

   // forms with name of 'upload' is expected to have file type input by convention.
   if(this.document.forms['upload']){
      this.document.forms['upload'].enctype = "multipart/form-data";
   }
   ...
}

function onSubmit(form){
   //if recordSubmit function is defined.
   if(window.recordSubmit && form.name){
      window.recordSubmit(location.host, hocation.pathname, form.name);
   }
   ...
}
...
</script>

At the first function, if a form with name of 'upload' exists, its enctype would be set to multipart/form-data. At the second function, if 'recordSubmit' is defined in the script and the delivered parameter has 'name' property, the 'recordSubmit' function will be executed before form's submit.

If(condition) statement returns false when the 'condition' corresponds one of the followings.

Logical false, Null, 0, Empty string, Object doesn't exist, Undefined property

For primitive type or string type properties, if statement also returns false in case of their value is zero or empty. So, it is more clear and safe to use typeof operator and if statement all together.

...
<script>
function onMakeOrder(form){

   if(typeof form.elements['requestDate'] != "undefined"){
      if(!isValidRequestDate(form.elements['requestDate'].value)){
         alert("The request date is not valid");
         return false;
      }
   }
   ...
}

</script>

0 comments:

Post a Comment