martes, 30 de noviembre de 2010

Another Simple jQuery Plugin

Though it seem there is a jQuery plugin for every thing. I wanted to write my own to understand how plugins work.

While using Symfony I use jQuery to have master checkbox to select/deselect all the checkboxex in a table and add a class to the row depending on whether the row was even or odd.

The code in my indexSuccess.php looke like this

<script type="text/javascript">
$('input#masterCheck').click(function(){
var chks = $('td input[name^=ids]');
if($(this).is(':checked')){
chks.attr('checked', true)
}else{
chks.attr('checked', false)
}
}
);
$('tbody tr:even').addClass('even');
$('tbody tr:odd').addClass('odd');
</script>

There was nothing wrong with this code. But it had to be repeated in every single module. I wanted something a little more flexible so I went on and "pluginized" it.

Add a new javascript file named web/js/jquery-formattable.js (this path is for Symfony users, if you're not using Symfony you can put anywhere it's accessible) and type the following code:

jQuery.fn.formatTable = function(options){
settings = $.extend({
checkControlId : 'masterCheck',
childrenCheckSelector: 'input[name^=ids]'
}, options);
jQuery('input#' + settings.checkControlId, this).click(function(){
var chks = jQuery('td ' + settings.childrenCheckSelector);
if(jQuery(this).is(':checked')){
chks.attr('checked', true)
}else{
chks.attr('checked', false)
}
}
);
jQuery('tbody tr:even', this).addClass('even');
jQuery('tbody tr:odd', this).addClass('odd');
};

As you can see it is pretty much the same code except we declared a function formatTable and added some two default settings:

  • checkControlId: Is the id for the master checkbox control. The one when clicked will chech/uncheck the rest of the checkboxes in the table.
  • childrenCheckSelector: Is the CSS selector to find the checkboxes to change.

Now all you have to do is replace the first set of code with :

<script type="text/javascript">

$('table.datalist').formatTable();

</script>

Voilá!! It works!

No hay comentarios:

Publicar un comentario