0

I am attempting to send the value of a select element as a parameter to an ajax request. However it will always send the initial value of the element on page load as opposed to the value of the current selection.

I have tried updating the variable by resetting it when the select box changes, but that didn't have any effect on the ajax request.

<select id="id_location">
  <option value="1">...</option>
  <option value="2">...</option>
  <option value="3">...</option>
</select>

<script>
var list = $("#id_location").val();

$(document).ready(function() {

$("#id_location").change(function(){
    list = $("#id_location").val();
})

$('#id_part_number').autocomplete({
    serviceUrl: '/lookup',
    width: 500,
    params: {location: list},   // <-------- This variable is not updating
    onSelect: function (suggestion) {
        var request = $.ajax({
            url: "/lookup",
            type: "GET",
            data: {"query": suggestion.data,
                   },
            dataType: "json"
            });
        request.done(function(msg) {
            $("#id_number").val(msg.number);
            $("#id_desc").val(msg.description);
            $("#id_par").val(msg.par);
        })
    }
});

})
</script>

I am a complete novice when it comes to javascript/jquery and haven't been able to come up with anything from googling. Any insight into solving this would be much appreciated.

Edit: The autocomplete function above is part of the external library jquery-autocomplete. It's purpose is to send the ajax request every time the element it is attached to, in my case an input field, is updated. I would like to send the current value of the #id_location element with the parameters in the request. Right now I have only been able to get it send the original value of the element when the page loaded and can't get it to update.

Del
  • 667
  • 7
  • 23
  • I do not need the $("#id_location").change(function()) at all. That is just one way I tried unsuccessfully to solve the problem. The $('#id_part_number').autocomplete part is the necessary part. – Del Apr 26 '14 at 02:53
  • Are there any javascript errors at all? Is the autocomplete list being updated? Use [Chrome](http://stackoverflow.com/questions/1820927/request-monitoring-in-chrome) or [Firebug](http://stackoverflow.com/questions/7412353/how-to-find-whether-ajax-request-successfully-send-by-fire-bug-add-on) to inspect the ajax request. Click the links if you don't know how. – mawburn Apr 26 '14 at 03:01
  • There are no errors at all. I am watching the request being sent and it goes through just fine and the autocomplete populates as expected, except the location parameter won't update to a new value when the selection has changed. – Del Apr 26 '14 at 03:06
  • Check my new answer, see if this works. – html_programmer Apr 26 '14 at 03:12

1 Answers1

2

Found the answer.

params:{location: function(){ return $('#id_location').val()}},
html_programmer
  • 18,126
  • 18
  • 85
  • 158