matt matt - 7 months ago 38
jQuery Question

How do I pass an extra parameter to Jquery Autocomplete field?

I'm using the JQuery Autocomplete in one of my forms.

The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.

This is how my form looks.


<select id="zipcode">

<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>


<input type="text" id="product"/>

<input type="submit"/>


And here is the JQuery code:

source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){



This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?


You need to use a different approach for the source call, like this:

  source: function(request, response) {
    $.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() }, 
  minLength: 2,
  select: function(event, ui){

This format lets you pass whatever the value is when it's run, as opposed to when it's bound.