3

When I click a control with id of Button1 it calls a function called getMakes, I want to be able to pass a parameter to it. In this case the id of the control that will be receiving data. What am I doing wrong?

$(function () {

        $('#Button1').click(getMakes("'#output'"))
        $('#buttonClear').click(function () {
            $('#output').html('');
        });
});
function getMakes(myVar) {   
$.ajax({
    type: "POST",
    url: "WebService.asmx/dbAccess2",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        var response = msg.d;
        $.each(response, function (index, value) {
            $(myVar).append(new Option(value, index));
        });
    },
    failure: function (msg) {
        alert('failure');
    }
});

}

3 Answers 3

5

OJ and Jacob have the right solution, but they didn't explain why. Your code,

$('#Button1').click(getMakes("'#output'"))

Passes the return value of getMakes to click. You're actually calling the function right then and there (when that line gets executed -- not when the user clicks it). That's not what you want, you actually want to call the function on the click event with the argument. To do that, you need to call a parameterless function that in turn calls your function with your arguments. Easiest way to do that is with an anonymous function, like the others have suggested.

Also note that your line of code has some extra quote marks and is missing a semi-colon.. not sure if that was intentional.

Sign up to request clarification or add additional context in comments.

Comments

4

Simple:

$('#Button1').click(function() {
    getMakes('#output');
});

Comments

0

Instead of

$('#Button1').click(getMakes("'#output'"))

.. (note you're missing a semicolon at the end).. Do this:

$('#Button1').click(function() { getMakes("'#output'"); });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.