use several JS function on form check - javascript

i have a select box to allow the user select what kind of form he need to fill in.
the 2 options are for a single person or someone from a group therefore some of the fieldsets that are in use in the single are switched with some from the group ones.
so for the single user i have this functions: singleinformation, winninginformation, reporterinformation, parentalinformation.
and for the group i have groupinformation, winninginformation, reporterinformation.
in the onsubmit i have another check() function that will check the check box and by the selection will call the right functions
function Check() {
if (document.getElementById("type").value=="s") {
return CheckSingleInformation();
return CheckWinningInformation();
}
else if (document.getElementById("type").value=="g") {
return CheckGroupInformation();
return CheckWinningInformation();
}
}
for some reason, after finishing the first function, if it returned without false it will send the form and not stop at the first error of the second function
what can i do to fix it?

onsubmit must have as value "return Check()". If you simply call Check(), returning values won't be used and it will continue with the submission.

never mind... found the answer :-)
first i have changed the main function to look like this:
function Check() {
if (document.getElementById("type").value=="s") {
CheckSingleInformation();
CheckWinningInformation();
}
else if (document.getElementById("type").value=="g") {
CheckGroupInformation();
CheckWinningInformation();
}
}
but then i found out it wont stop after the first function so i changed it to be like this
function Check() {
if (document.getElementById("type").value=="s") {
if (CheckSingleInformation()==false) {return false}
if (CheckWinningInformation()==false) {return false}
}
else if (document.getElementById("type").value=="g") {
if (CheckGroupInformation()==false) {return false}
if (CheckWinningInformation()==false) {return false}
}
}
is that the right way?

2 notes:
Returning "true" from the onsubmit() event will stop it from propagating; the form won't be submitted (usually is the behaviour you want when you're doing an AJAX posting)
checkWinningInformation(); will never be called in both blocks, since the statement prior to it is a "return" which actually jumps out of the method execution... that can't be what you want, can it?

Check nested conditions,
function Check() {
if (document.getElementById("type").value=="s") {
if(!CheckSingleInformation()){
return CheckWinningInformation();
}
return true;
}
else if (document.getElementById("type").value=="g") {
if(!CheckGroupInformation()){
return CheckWinningInformation();
}
return true;
}
}

Return is used in a function for two reasons:
You want the script to stop executing if something happens.
You want the function to return a value to the calling function.
You used return like so:
return CheckSingleInformation(); <-- exit here
return CheckWinningInformation();
Your script will "exit" (or submit the form) right after the first return!
What you could do to resolve this: Call CheckWinningInformation() at the end of CheckSingleInformation() as well as at the end of CheckGroupInformation().

Using logical AND operator (&&) would be fine.
so the following code :
function Check() {
if (document.getElementById("type").value=="s") {
return CheckSingleInformation();
return CheckWinningInformation();
}
else if (document.getElementById("type").value=="g") {
return CheckGroupInformation();
return CheckWinningInformation();
}
}
could be :
function Check() {
if (document.getElementById("type").value=="s") {
return (CheckWinningInformation() && CheckSingleInformation());
}
else if (document.getElementById("type").value=="g") {
return (CheckWinningInformation() && CheckGroupInformation());
}
}

Related

the if statement is not running and returning the string [duplicate]

I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
You can just use return.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)

Returning true/false after multiple functions

function topFunction() {
if (checkUserRole()) {
//trying to figure out if I will hit this line
}
}
checkUserRole() {
anotherFunction()
}
anotherFunction() {
return true;
}
So what I am asking is, will that original checkUserRole() be considered true in this scenario? Or do I somehow need to pass the true up from anotherFunction() to checkUserRole()?
No, you will need to explicitly return it up:
function topFunction() {
if (checkUserRole()) {
//trying to figure out if I will hit this line
}
}
checkUserRole() {
return anotherFunction();
}
anotherFunction() {
return true;
}
Without the return in the checkUserRole function the true that comes back from anotherFunction gets lost. The way you had originally written it returns nothing from checkUserRole, which means that it will fail the "truthy" test in the if statement in topFunction no matter what happens in either anotherFunction or checkUserRole.
You're missing the return statement inside the checkUserRole method

Check if function returns true to execute another function

I have written a form validation using JS which ends with return(true);
function check() {
....validation code
return(true);
}
All I want is, need to check if check() function returns true, I want to execute another function.
Code I have tried is as follows:
if(check() === true) {
function() {
//Another function code
}
}
You should use return true; and your if statement doesn't need the === true comparison.
function check() {
//validation code
return true;
}
if(check()) {
//Another function code
}
JSFIDDLE
First of all, return is not a function, you can just do this:
return true;
Now, to only execute myFunction if check returns true, you can do this:
check() && myFunction()
This is shorthand for:
if(check()){
myFunction();
}
You don't need to compare the return value of check with true. It's already an boolean.
Now, instead of myFunction(), you can have any JavaScript code in that if statement. If you actually want to use, for example, myFunction, you have to make sure you've defined it somewhere, first:
function myFunction() {
// Do stuff...
}
You just need to modify your first code snippet. return is a keyword, what you are trying to do is to execute it as a function.
function check() {
....validation code
return true;
}
You'll need to change your 2nd snippet slightly, to execute the function too however... The simplest way is to wrap it as an anonymous function using curly braces:
if(check()) {
(function() {
//Another function code
})();
}
You're not calling the function in your affirmative clause, only declaring it. To call an anonymous function do this:
(function (){...})()
You could type
$this.myFunction=function(){
//code here
}
and to execute some code if a the myFunction function is true, you could use booleans
such as e.g.
if(//your function is true){
and so on

javascript confirm function ok and cancel returns same result

Here in result() method, whenever it comes to else part, I need to get out of the function callthis().
It should not execute kumar() function.
Is this possible?
Actually, I can use like this
if(result) //if this method is true, it will come inside
{
kumar();
}
But this is not I want. while returning false from result() method, it should get out of the loop function calthis()
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
result();
kumar();
}
}
function result()
{
var res = confirm("are you wish to continue");
if(res==true)
{
return true;
alert("inside if result");
}
else
{
return false;
}
}
function kumar()
{
alert("inside kumar");
}
Click here
There's a bunch wrong here.
First, if (result) just tests whether the variable result contains a truthy value, it doesn't actually invoke the function. If you want to test the return value of the function, you need
if (result()) {
Secondly, you're not understanding that return immediately leaves the current function. You can't meaningfully do this:
if(res==true)
{
return true;
alert("inside if result");
}
That alert cannot be reached. The function returns immediately when return true is encountered.
Thirdly, to exit callThis early, you simply need to return early. It's up to the function callThis to conditionally return; you cannot force a return from down inside the result function. A function cannot forcibly return out if the context that called it. It's not up to the internals of the result function to determine if kumar should run. You cannot influence the path of execution in the calling method directly. All result can do is return something, or (needlessly complex in this case) accept a callback and conditionally execute it.
Just return from callThis if the result of result() is false:
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
if (!result()) return;
kumar();
}
}
To exit any function simply use return;
However it seems like you want to call a function if the user clicks confirm, is that correct? If so:
var res = confirm("are you wish to continue");
if (res === true)
{
kumar();
}
If you want to call a function if the user does not click confirm:
var res = confirm("are you wish to continue");
if (!res)
{
kumar();
}
You got a lot of confusing code going on there, but if the idea is to stop a function, simply use "return false;" and the code execution stops

Early exit from function?

I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
You can just use return.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)

Categories

Resources