Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call function with parameter in jQuery

Tags:

jquery

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');
    }
});

}

like image 761
The Muffin Man Avatar asked Jan 25 '26 05:01

The Muffin Man


2 Answers

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.

like image 157
mpen Avatar answered Jan 27 '26 23:01

mpen


Simple:

$('#Button1').click(function() {
    getMakes('#output');
});
like image 41
Jacob Relkin Avatar answered Jan 27 '26 21:01

Jacob Relkin