JQuery Quick Tip: Custom Attributes

For quite some time,  whenever I needed to pass something like a database table row index from a webpage to a PHP script I would do string manipulation to get the data.

Something like this:

<div class="tdiv" id="td_4932">Something interesting</div>


var tid=this.id;

tid = tid.replace('td_','');

//now tid = the index



In an epic /facepalm moment I realized that I’ve been doing it the hard way.   I realized this when I had to pass several bits of information back to the PHP script.  The string manipulation code would be kludgetastic.

It was simple. Put the parameter as a custom attribute!

Like this:

<div class="tdiv" id="tdept" dept="4932">Something interesting</div>  //the dept attribute points to the target department in the database


var tid = $('#tdept').attr('dept');

console.log("The dept index is " + tid);




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s