jQuery change event on checkbox

April 6th, 2010

A lot of times, you’ll want to call a javascript function when a checkbox is changed from unchecked to check and vice versa.  Up until the release of jQuery 1.4, the obvious way to do it (the jQuery .change() event) did not work properly across all versions of Internet Explorer.  Instead, you had to check for the .click() event.  This was an accessibility problem because it did not fire when a user changed a checkbox with the space bar instead of by clicking.  Well, now we can rejoice.  The following code snippet works exactly how you think it would across browsers, including IE.

<!-- Load jQuery, and the necessary html -->
<script type='text/javascript src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<input type='checkbox' name='my_checkbox' value='true' checked='checked'>
  1.     $(":checkbox").change(function(){
  2.         if($(this).attr("checked"))
  3.         {
  4.             //call the function to be fired
  5.             //when your box changes from
  6.             //unchecked to checked
  7.         }
  8.         else
  9.         {
  10.             //call the function to be fired
  11.             //when your box changes from
  12.             //checked to unchecked
  13.         }
  14.     });
  15. });

View Demo

Easy ajax with jQuery and PHP

March 29th, 2010

When I was first learning about web programming, it was difficult to grasp how javascript can interact with PHP.  How do I manipulate data in the database with a client-side language?  The answer, of course, is ajax, and if you’ve never used ajax, now is the time to learn how.

What is ajax?

Ajax is not a singular technology, it is a collection of technologies used for asynchronous communication between the client and server i.e. javascript grabbing data from a PHP script and displaying it on the page without refreshing the page.  This is done through a DOM api called XMLHttpRequest, and I would encourage you to read a more in-depth view on its Wikipedia page.  While this has some SEO implications, it also gives the programmer or designer a way to build rich, dynamic internet applications that don’t require a propriety plugin like Flash or Silverlight.  Now that you have a basic understanding of ajax, lets try it out.

In this tutorial and demonstration, I will take a number from the user with an input box, and grab the row with that ID from the database and display it.  This is not a useful example, but it does demonstrate the principles of moving data back and forth between the client and the server, and how we can display the data.

View the demo

Read the rest of this entry »