...

View Full Version : JQuery: name of a function as a callback instead of the actual function



nikos101
10-12-2009, 03:13 PM
Can you give the name of a function as a callback instead of the actual function in JQuery

ie


function doWhatever($e) {
$e.preventDefault();

if ($('#amount').val() == '' ) {
alert("Please enter an amount");
return;
}
if ($('#amount').val().match(/[^0-9\.]/g)) {
alert("Your amount contains invalid characters");
return;
}
if ($('#amount').val().match(/.*\..*\..*/)) {
alert("Only 1 decimal point allowed");
return;
}
/* if ($('#amount').val().match(/^[0]+$/)|| $('#amount').val().match(/^([0]+)?.([0]+)?$/) ) {
alert("Your number cannot equal zero");
return;
}*/


$('#value').attr("value", ($('#amount').val() * $('#cur2').val()/$('#cur1').val()).toFixed(2));
}

$(document).ready(function () {
$('#submit').click(
doWhatever($e)
)



});

seco
10-12-2009, 03:55 PM
$(document).ready(function () {
$("#submit").click(function(){
doWhatever($e);
});
});

Fumigator
10-12-2009, 06:19 PM
I see this a lot, where the function is assigned to a variable and the variable is then used as the callback:



var whateverFunction = function ($e) {
$e.preventDefault();

if ($('#amount').val() == '' ) {
alert("Please enter an amount");
return;
}
if ($('#amount').val().match(/[^0-9\.]/g)) {
alert("Your amount contains invalid characters");
return;
}
if ($('#amount').val().match(/.*\..*\..*/)) {
alert("Only 1 decimal point allowed");
return;
}

$('#value').attr("value", ($('#amount').val() * $('#cur2').val()/$('#cur1').val()).toFixed(2));
}

$(document).ready(function () {
$('#submit').click(whateverFunction)
});

nikos101
10-12-2009, 06:20 PM
I don't like hacks but this is the best there is :)

thx

rnd me
10-13-2009, 04:42 AM
you were almost there in your first post, just omit the parens so that you pass click the function instead of the result of executing the function...


$(document).ready(function () {
$('#submit').click(doWhatever);
});
it's not a hack at all, in fact it's a good practice to name all your functions.

seco
10-13-2009, 05:53 AM
if you want to use more than one function on click use the one i posted.

nikos101
10-13-2009, 10:43 AM
you were almost there in your first post, just omit the parens so that you pass click the function instead of the result of executing the function...


$(document).ready(function () {
$('#submit').click(doWhatever);
});it's not a hack at all, in fact it's a good practice to name all your functions.
ULTRA cool, its the same as FLEX



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum