I have this code:
<script language="javascript">
$(function() {
$('#items,#button-search').hide();
$("#companies").click(function() {
$(this).attr("value","");
$('#address,#new-company-form').empty();
});
$( "#companies" ).autocomplete({
source: ";companies",
minLength: 2,
select: function( event, ui ) {
$('#address').show();
if(ui.item.id == "create-new-company") {
// call the new company form
$('#address').empty();
//$('#new-company-form').load('/companies/;new_resource?type=company #autoform',
$('#new-company-form').load(';company_form #autoform');
} // end 'if'
else
{
$('#new-company-form').empty();
$.ajax({
type: 'GET',
url: ';addresses?company=' + ui.item.id,
dataType: 'json',
// process the addresses
success: function(json) {
var opts = '';
$.each(json, function(k, v) {
opts += '<option value="'+k+'">' + v + '</option>';
});
$('#address').html('<select>' + opts + '</select>');
// we click on a select value .change(function () {
$("#address").change(function () {
var id = $(":selected", this).val();
if(id == "create-new-address") {
$('#new-address-form').load(';address_form #autoform');
}
else
{
alert('Request completed' + id);
// pass the id value to the application
}
}) // end click event
}
}); //end ajax call to address
} // end else
} // end select address
}); // end autocomplete
}); // end function
</script>
everytime i run the form, the ‘alert(‘Request completed’ + id);’ on line 41 displays 4 times when i click on an option value.
Is there any way to improve this?
Thanks
Norman
You are setting jQuery event handlers inside your autoComplete select function. So, everytime the
selectfunction for autocomplete is called, you do this:That means that this event handler is getting added over and over again (thus it gets called multiple times). You need to add that event handler once outside the autocomplete framework, not inside the autocomplete function or the select handler.
I think you want it to be like this: