Reputation: 20004
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');
}
});
}
Upvotes: 3
Views: 11039
Reputation: 282885
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.
Upvotes: 5
Reputation: 29401
Instead of
$('#Button1').click(getMakes("'#output'"))
.. (note you're missing a semicolon at the end).. Do this:
$('#Button1').click(function() { getMakes("'#output'"); });
Upvotes: 0
Reputation: 163248
Simple:
$('#Button1').click(function() {
getMakes('#output');
});
Upvotes: 4