Thursday, March 28, 2013

Javascript and the this statement

What to know:
PHP, basic Javascript.


Often times in php, I'm generating lists of objects -- specifically html objects -- and I will include a Javascript link to process the information.  That, in itself, is not my favorite option but php is server and Javascript is client (Browser).  This relationship can be a headache but here are some tips to aid the pain.

First things first.  Javascript does provide a painless way to extract information from any object -- this.  The 'this' object gives you all the tools you need to gather anything you want about an object and pass it along to a procedure. 

Example
<input id='fred' value='bob' onclick='DoSomething (this) >this is nice</input>

This is your gateway to freedom.  The 'this'.  Don't believe me?

In your function

function DoSomething (Value)
{


}


You can extract:
The ID of the object, the value of the object and the text past the object

Now, let's see how

function DoSomething (Value)
{

   alert (Value.id);   // get the ID of the object or in this case 'fred'
   alert (Value.value) // get the value of the object or in this case 'bob'
   alert (Value.innerHTML) // get the text or in this case 'this is nice'
}

Now if you're worried about extracting information about an object, you need worry no more.

I'm no expert on Javascript and try to avoid it when I can but I can't deny its usefulness.



 

No comments:

Post a Comment