The random eclecticisms of loonytoons

Jquery .live and .livequery

I recently had a problem where I was trying to insert some product information into a page, with the information shown changed depending on which product was selected from a drop down list.

Here is the select list and the div that I wanted the extra information to be displayed into:

<select name="product" id="product">
<option value="">Select product...</option>
<option value="Product 1">Product 1</option>
<option value="Product 2">Product 2</option>
<option value="Product 3">Product 3</option>
<option value="Product 4">Product 4</option>
</select>

<div id=”product_info”>
</div>


To make this work I needed to use javascript, and am a big fan of jquery, so I included the jquery js file in my site header and added the following code at the top of the page:

<script type="text/javascript">
$("document").ready(function ()
{
$("#product").live("change",function(productExtra)
{
var selectedOption = $('#product').val();
$("#product_info").load("/productinfo.php", {'product': selectedOption} );
});
});
</script>

This uses the jquery .live event to trigger the function productExtra whenever the element with the id ‘product’ changes (or at least that was the plan, more on this later).

The .load event goes off the url provided, eg. /productinfo.php, passes in ‘selectedOption’ as the ‘product’ via POST, and returns the html output from that file in the div with id ‘product_info’.

This was brilliant and worked really well, except that of course it didn’t work in IE. A little digging around and I realised that ‘change’ isn’t actually currently supported as an event value in .live (though hopefully it will be soon). Firefox might have the sense to know what to do with it but IE was just left aimlessly wandering in the dark and so didn’t do anything.

Luckily it’s really easy to fix though. Just download the live query plugin, include the file in your page header and change the line that reads

$("#product").live("change",function(productExtra)

to read

$("#product").livequery("change",function(productExtra)

and IE should now be able to handle this event without throwing it’s toys out of the pram. There’s an interesting discussion on the difference between .live and livequery here, otherwise more information can be gained from reading the jquery and live query plugin documentation.

Share

2 thoughts on “Jquery .live and .livequery

  1. Luis Aveiga says:

    Interesting… IE8 works now with live, i guess…
    I was looking for the difference between these methods, I’ll read the link in your article.

    Probably it’s a way to have a .live function for older versions of jquery??

    Thanks!

  2. loonytoons says:

    Yeah, looks like this has been fixed in the latest version of jquery. Yay!

Leave a Reply

Your email address will not be published. Required fields are marked *