jquery call function by name

i have function

<script type="text/javascript">
    $(function () {
        $("#search").click(function() {
            var text = $("#searchText").val();
            $.getJSON("Search", { world: text, filter: text }, function(data) {
                $("tr.DataRow").toggle(false);
                for (i = 0; i < data.length; i++) {
                    $("#obj" + data[i]).toggle(true);
                }
            });
        })            
    });


</script>

now i have another function

<script type="text/javascript">

    $(function() {
        $('#searchText').bind('keypress', function(e) {
            if (e.keyCode == 13) {

            }
        });
    });
</script>

how can i call first function from second function?

Answers


You can raise a click event on the element you registered the first function

<script type="text/javascript">

    $(function() {
        $('#searchText').bind('keypress', function(e) {
            if (e.keyCode == 13) {
                $('#search').click(); // Raise a click event on #search element
            }
        });
    });
</script>

Extract the logic from the first event handler into a named function:

function doSearch() {
    var text = $("#searchText").val();
    $.getJSON("Search", { world: text, filter: text }, function(data) {
        $("tr.DataRow").toggle(false);
        for (i = 0; i < data.length; i++) {
            $("#obj" + data[i]).toggle(true);
        }
    });
}

You can now pass doSearch by name to the click handler:

    $(function () {
        $("#search").click(doSearch);
    });

and explicitly invoke it from within the key handler:

    $(function () {
        $('#searchText').bind('keypress', function(e) {
            if (e.keyCode == 13) {
                doSearch();
            }
        });
    });

// first function
$(function() {
  $.yourFavoriteFunctionName = function() {
    // the code for the first function
  };
  $.yourFavoriteFunctionName();
});

then

// second function
$(function() {
  // whatever
  if (foo)
    $.yourFavoriteFunctionName();

you could give it a name? am I missing something?

edit: to get this right

<script type="text/javascript">
function() myfunction{
    var text = $("#searchText").val();
    $.getJSON("Search", { world: text, filter: text }, function(data) {
        $("tr.DataRow").toggle(false);
        for (i = 0; i < data.length; i++) {
            $("#obj" + data[i]).toggle(true);
        }
    });
}

$(function(){
    $("#search").click(myfunction);
});
</script>

and then

<script type="text/javascript">

$(function() {
    $('#searchText').bind('keypress', function(e) {
        if (e.keyCode == 13) {
            myfunction();
        }
    });
});
</script>

Need Your Help

How to read a file from a jar file?

java file text jar filereader

I have a file in a JAR file. It's 1.txt, for example.