shah rushabh
shah rushabh

Reputation: 41

jQuery inside function calling not working

How can I call search function? lot's of code written outside search function so I want to execute all code How can I do this please help me.

jQuery:

$(function(){
        function search(){
            alert("Hello World");
    }
})

HTML Code:

<select onchange="search();">
    <option value="1">Hello</option>
</select>

Upvotes: 1

Views: 404

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Any functions you call from onxyz-attribute-style event handlers must be global functions. That's one of the many reasons not to use them. Your search isn't global, it's nicely contained within your ready handler. Which is good, globals are a Bad Thing™.

Hook up the function within your ready callback. Any selector for the select element will do; here's an example using an ID, but it doesn't have to be an ID:

<select id="the-select">
    <option value="1">Hello</option>
</select>

and

$(function(){
    $("#the-select").on("change", search);
    function search(){
            alert("Hello World");
    }
})

If you don't call search from any other code, you can combine that:

$(function(){
    $("#the-select").on("change", function search(){
    // Name here is optional --------------^--- but handy for debugging
    // if an error is thrown in the function
        alert("Hello World");
    });
})

Upvotes: 6

Related Questions