Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I name and call a jQuery function?

Tags:

I have the following:

 $('#EID').change(function () {
                $.ajax({
                    url: "/Administration/stats",
                    data: { DataSource: $('#DataSource').val(),
                            EID: $('#EID').val()
                    },
                    success: function (data) {
                        $('#TID').html(data);
                    }
                });
            });

This works good but I want to be able to call the function () at other times and not just when EID changes. Can someone show me how I can pull out the function code into a separate block with a name and then call that function name.

like image 856
Samantha J T Star Avatar asked Nov 01 '11 07:11

Samantha J T Star


People also ask

How do you define and call a function in jQuery?

Answer: Use the syntax $. fn. myFunction=function(){}

Can we use named function in jQuery?

The idiomatic way to use named functions is to do: function doSomething(thing){ return thing + 1 } doSomething(3);

Can we call jQuery function in JavaScript?

You can directly write your jQuery code within a JavaScript function. See below code. I have placed a button on my page which makes a call to a Javascript function "Test()".

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.


1 Answers

function doSomething() {
    $.ajax(...);
}

$('#EID').change(doSomething);

Note that you must not add () after the function name since you want to pass the function, not its return value.

In case you wanted to pass some parameter to the function, you'd do it like this:

function doSomething(someParam) {
    $.ajax(...);
}

$('#EID').change(function() {
    doSomething(whateverSomeParamShouldBe);
});
like image 145
ThiefMaster Avatar answered Oct 02 '22 07:10

ThiefMaster