Book Image

PHP jQuery Cookbook

By : Vijay Joshi
Book Image

PHP jQuery Cookbook

By: Vijay Joshi

Overview of this book

As web technology evolves, the gap between desktop applications and web applications continues to vanish. And what better way to bridge that gap, for your own website, than using the best two open source technologies in the market: PHP and jQuery. The power-combo of these two is leading the way in revolutionizing the RIA world. Although they are easy to integrate, finding or figuring out how to do what you want to do is rather arduous.The PHP jQuery Cookbook will be your handy guide with walkthroughs of common integration tasks and problems that will help you master the possibilities available using the PHP and jQuery combo. You will learn quick solutions to necessary tasks to integrate the power of two of the best known and most widely used web technologies of today – PHP on the server side and jQuery on the client side. Glide through the basics and move to advanced topics to create dynamic and interactive web applications with this book in hand.This book covers a wide array of technical aspects of creating an interactive website. Apart from basics of PHP and jQuery, you will go through advanced topics like creating plugins, validating controls, and useful utilities that you will be able to use as stand-alone tools. AJAX, the key technique of browser-server communication is covered in detail. You will also learn to use JSON, which is becoming preferred as a mode of data interchange over XML, both in web applications and web services.The book also covers database interaction, which is an important part of any dynamic web application. You will also gain expertise in debugging JavaScript with the help of useful tools that will save you hours of tedious manual debugging.Most importantly, by using jQuery and PHP together, you will be able to develop applications that are compatible with all major browsers, with no need to write code targeted at specific browsers!
Table of Contents (17 chapters)
PHP jQuery Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Binding and unbinding elements


This recipe will demonstrate how you can attach events to DOM elements using the .bind() method and how to remove them using the .unbind() method.

Getting ready

Get a latest copy of the jQuery library to use with this recipe.

How to do it...

  1. Create a new file, in a directory named chapter1, and name it as binding.html.

  2. Write the HTML markup to create some HTML elements. Create an unordered list with the names of some countries. After that, create a select box containing names of continents as options. Finally, create a button that will be used to remove the event handler from the select box.

    <html>
      <head>
        <title>Binding Elements</title>
        <style type="text/css">
          ul { background-color:#DCDCDC; list-style:none; margin:0pt; padding:0pt; width:250px;}
          li { cursor:pointer; margin:10px 0px;}
        </style>
      </head>
      <body>
        <ul>
          <li>India</li>
          <li>USA</li>
          <li>UK</li>
          <li>France</li>
        </ul>
    
        <select> 
          <option value="Africa">Africa</option>
          <option value="Antarctica">Antarctica</option>
          <option value="Asia">Asia</option>
          <option value="Australia">Australia</option>
          <option value="Europe">Europe</option>
          <option value="North America">North America</option>
          <option value="South America">South America</option>
        </select>
    
        <input type="button" value="Unbind select box"/>
      </body>
    </html>
  3. It's time to add some jQuery magic. Attach a click event handler to list items using the .bind() method, which will set the background color of the clicked item to red. Attach the change event handler to the select box, which will display the value of the selected item. Finally, add a click handler to the button. Clicking on the button will remove the event handler from the select box.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function ()
      {
        $('input:text').bind(
        {
          focus: function()
          {
          $(this).val('');
          },
          blur: function()
          {
            $(this).val('Enter some text');
          }
        });
    
        $('li').bind('click', function()
        {
          $(this).css('background-color', 'red');
        });
        
        $('select').bind('change', function()
        {
          alert('You selected: '+ $(this).val());
        });
        
        $('input:button').bind('click', function()
        {
          $('select').unbind('change');
        });
      });
    </script>
  4. Run the binding.html file in your browser and click on some items in the list. The background color of each item clicked upon will change to red. Now select some value from the select box and you will see an alert box that displays the selected value as shown in the following screenshot:

    Clicking on the Unbind select box button will remove the change event handler here and the selection of a value from the combo box will now do nothing.

How it works...

jQuery uses the .bind() method to attach standard JavaScript events to elements. .bind() takes two parameters. The first parameter is the event type to attach. It is passed in string format, and event types such as click, change, keyup, keydown, focus, blur, and so on can be passed to it. The second parameter is the callback function, which will be executed when the event fires.

In the previous code, we used .bind() for the list items to attach a click handler. In the callback function, $(this) refers to the element that fired the event. We then use the .css() method to change the background color of the element that is clicked upon.

Similarly, we attached the change event to the select box using the .bind() method. The callback function will be called each time the value of the select box is changed.

The input button has also been attached to a click event. Clicking on the button calls the .unbind() method. This method accepts an event type name and removes that event from the element. Our example code will remove the change event from the select box. Therefore, changing the value of the select box will not display any further alerts.

There's more...

Binding multiple events

Multiple events can also be attached using the .bind() method. The following code attaches two events focus and blur to a textbox. Focusing on a textbox will empty it, whereas taking the focus away from it will put some text in it.

$('input:text').bind(
{
  focus: function() 
  {
    $(this).val('');
  },
  blur: function() 
  {
    $(this).val('Enter some text');
  }
});

Tip

Note that this functionality was added in Version 1.4 of jQuery. So, make sure that you have the correct version before running this code.

Shortcut method for binding

Instead of using .bind(), events can be attached directly by using shortcut event names to elements. For example, $(element).click(function() { }); can be written instead of using $(element).bind('click', function() { });.

Other events can be attached similarly.

Triggering events

Events can also be triggered from the code. For this we have to pass the event name without any parameter.

$(element1).click(function()
{
  $(element2).keydown();
});

The above code will execute the keydown event of element2 when element1 is clicked.

Common event types

Here is a list of some common events that can be passed to the bind() and unbind() methods.

blur

focus

load

unload

scroll

click

dblclick

mousedown

mouseup

mousemove

mouseover

mouseout

change

select

submit

keydown

keypress

keyup

Unbinding all events from an element

If no parameter is passed to the .unbind() method, it will remove all event handlers associated with the specified element.

$(element).unbind();