0

I have several jquery ui objects and they all have a similar callback:

$(function() {
    $("#my_list").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: "POST",
                url: "api",
                data: {
                    term: request.term,
                },
                success: response,
                dataType: 'json',
                minLength: 0,
            });

        },
        minLength: 0,
        select: function(event, ui) {
              $('something').appendTo("#another_list");
            }

        }
    });
});

If I could pass the "my_list" and "another_list" there as parameters, the code would be much cleaner. How can this be done?

1
  • I don't understand in which function you want to get the "my_list" and "another_list" as parameters Commented Apr 20, 2016 at 21:36

1 Answer 1

1

just wrap that code in a function?

function initAutocomplete(list1, list2){
    $(list1).autocomplete({
        source: function(request, response) {
            $.ajax({
                type: "POST",
                url: "api",
                data: {
                    term: request.term,
                },
                success: response,
                dataType: 'json',
                minLength: 0,
            });

        },
        minLength: 0,
        select: function(event, ui) {
              $('something').appendTo(list2);
            }

        }
    });
}

$(function(){
  initiAutocomplete('#my_list', '#another_list');
  initiAutocomplete('#my_second_list', '#another_list_part_deux');
});
Sign up to request clarification or add additional context in comments.

2 Comments

That worked great. I just have a silly question. Am I correct that jquery-ui uses the callback signature $(function(){}); and tell it what event to trigger it on (like click event)?
$(function(){}) is a shorthand for $(document).ready. that it, it waits until the dom is fully loaded before executing any code within that callback. its not specific to jquery-ui

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.