Reputation: 434
I have this simple javascript function which calls other 2 functions:
<script type="text/javascript" language="javascript">
function mainfunction() {
function1()
function2()
}
function function1() {
if (//some test) {
alert('test function1');
return false;
}
}
function function2() {
if (//some test) {
alert('test function2');
return false;
}
}
</script>
i call mainfunction()
like this:
<form id="form1" runat="server" onSubmit="return mainfunction()">
or like this:
<asp:Button ID="btntest" runat="server" Text="test button" OnClientClick="return mainfunction()" />
btntest
is a button that just calls some class which redirects to another page.
function1()
or function2()
then the button will not get executed, which is what i want. but...:mainfunction()
then alert in each function works but return false;
doesn't seem to work because the button unfortunately gets executed.why is that? how can i call the 2 functions and let their return false;
work?
Upvotes: 1
Views: 650
Reputation: 40448
Your mainfunction
is not returning anything. Try this:
function mainfunction() {
return function1() && function2();
}
As mentioned in the comments, to have your mainfunction
working properly, you have to alter your other functions to always return either true
or false
:
function function1() {
if (//some test) {
alert('test function1');
return false;
}
return true;
}
EDIT
A funny hack to have both functions being executed and still return true
only when both functions are true
:
function mainfunction() {
return (function1() + function2()) === 2;
}
Upvotes: 1
Reputation: 266
Try this:
<asp:Button ID="btntest" runat="server" Text="test button" OnClientClick="mainfunction(); return false;" />
This will works as well:
<asp:Button ID="btntest" runat="server" Text="test button" OnClientClick="return mainfunction();" />
but you will need to change mainfunction:
function mainfunction() {
function1();
function2();
return false;
}
Upvotes: 0
Reputation: 66178
mainfunction
doesn't return anything, you aren't using the return values from either function1
or function2
To prevent a form from submitting, you need the handler itself to return false, for example:
function mainfunction() {
function1();
function2();
return false; // prevent form submission
}
Returning undefined (what you're doing right now in the example in the question) is not sufficient.
Upvotes: 0