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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With