21

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.

3 Answers 3

48
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);
});
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks very much. This is exactly what I need. If I wanted to pass the parameter $('#EID').val() then how would I declare the parameter and then use it inside of the function?
@Samantha: It's usually best to do this wrapped in a function containing all of your stuff (called a "scoping function") because otherwise you create global symbols, and the global space in web browsers is crowded enough already. Two examples: pastie.org/2792207
@Samantha: " If I wanted to pass the parameter $('#EID').val() then how would I declare the parameter and then use it inside of the function?" Exactly the way ThiefMaster demonstrated in the second half of his answer, example: pastie.org/2792210
Is a semi-colon needed after the function definition? I can't seem to get the code to work.
Then show the code... a semicolon is almost never required in JS.
|
0

Well , the other thing you can do for someone looking for answer now is to trigger the function

$('#EID').change (function (){
    //your code here;
});

Some other function or code you want to call the previous unnamed function , you can simply do;

$('#classOrId).eventYouwannaUse (function (){
$('#EID').change ();
 });

Comments

0

Or you can use on(); function and then define the function name

$('#EID').on('change' , ChangeEventfuncCode);
function ChangeEventfuncCode(){
 //your code ......
}

And then call the function anywhere you want..;

$('.classOrId').whateverEvent(function (){


//your code......
ChangeEventfuncCode();
});

1 Comment

duplicate answer, remove one.

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.