I have many function inside one main function validate which doesn't work for some reason.However if the function validate contain a single function it works
function validate() {
return textcheck("txtname");
return numcheck("txtnum");
// textcheck and numcheck function are here
//doesn't work
}
function validate() {
return textcheck("txtname");// works fine
}
function validate() {
return numcheck("txtnum"); // works fine
}
why does 2 return inside a function don't work
Why it doesn't work
return exits a function, so code after the first return will never run.
Consider these functions:
function logs() {
console.log('I have been called');
return;
}
function doesNotLog() {
return;
console.log('I will not be called');
}
The first function does log a message to the console because console.log is called before return.
The second function doesn't, because return exits the function before console.log is called.
Fixing your example
If you want to return true if both textcheck and numcheck return a truthy value, you could use the logical AND operator &&:
// Returns true if both checks pass
function validate() {
return textcheck("txtname") && numcheck("txtnum");
}
If you need either of the two tests to pass, use the OR operator ||:
// Returns true if either check passes
function validate() {
return textcheck("txtname") || numcheck("txtnum");
}
If you want to return the status of each individual check, you could return an object:
function validate() {
return {
textCheck: textcheck("txtname"),
numCheck: numcheck("txtnum")
}
}
return exits the function when it's encountered, so your second return will never be reached.
If your goal is to return a truthy value* if either of two function calls returns a truthy value, you can use ||:
function validate() {
return textcheck("txtname") || numcheck("txtnum");
}
That calls textcheck and, if it returns a truthy value, returns that value; if textcheck returns a falsey value, it calls numcheck and returns its result.
If you want to return a truthy value if both of two functions returns a truthy value, you can use &&:
function validate() {
return textcheck("txtname") && numcheck("txtnum");
}
That calls textcheck and, if it returns a falsey value*, returns that value; otherwise it calls numcheck and returns its result.
I suggest working through some basic JavaScript tutorials.
* "truthy value" and "falsey value": JavaScript's && and || operators don't always result in true or false like they do in many other languages. Instead, they look for "truthy" values (values that coerce to true) or "falsey" values (values that coerce to false). The falsey values are 0, "", NaN, null, undefined, and of course, false; the truthy values are everything else.
Return in function terminate him.
If you want to validate two (or more) values use one return statement.
function validate() {
return textcheck("txtname") && numcheck("txtFname");
}
This solution may help you if you need to return 2 values at the same time. You just need to return a json object
function validate() {
return {
txtname : textcheck("txtname"),
txtnum : numcheck("txtnum")
}
}
After you call the function, you can get your values like this :
var result = validate();
// result.txtname
// result.txtnum
Looking at your code, I assume you want the validate() return you success (true) if both textcheck() and numcheck() succeed. Try this -
function validate() {
return textcheck("txtname") &&
numcheck("txtnum");
}
Related
$("#submit").click(function()
{
function checkZeros()
{
if ([0] == 0) {
if ([1] != '.') {
alert("alert message");
return false;
}
}
}
checkZeros($("#user-input-currency").val());
if(!$.isNumeric($("#user-input-currency").val())) {
alert("Please provide price in numeric value");
return false;
}
})
I have function that checks if user-input-currency first number is 0 followed with '.' if not then gives alert, and returns false so the user can input right value. but in my case I get the alert message but page still refreshes.
what could be the problem here?
The next code that checks isNumeric works correct returns alert message and doesnt refreshes page.
Your return is in another scope than your click handler, so even if checkZeros returns false, your click handler wont stop.
You can use the following instead:
if(checkZeros($("#user-input-currency").val() === false)) return false;
The strict comparison here is used since your function doesn't have a return trueand functions returns undefined by default.
You can, for a better readability, change your function so it always returns a boolean and simplify your if to:
if(checkZeros($("#user-input-currency"))) return false;
p.s.: your code doesn't make sense, is it pseudo code?
Your click handler callback is not returning any value as only the checkZeros function is returning false value.
So you have to return the value which checkZeros function is returning to the click handler so that it won't proceed to submit.
$("#submit").click(function() {
function checkZeros() {
if ([0] == 0) {
if ([1] != '.') {
alert("alert message");
return false;
}
}
}
if (!$.isNumeric($("#user-input-currency").val())) {
alert("Please provide price in numeric value");
return false;
}
// in your case checkZeros function returns false, a function explicitly returns undefined if you haven't return any value, so you have to use conditional operator here
return !checkZeros($("#user-input-currency").val()) ? false : true;
})
This is my code
function nameIsDuplicate(name){
objects = $("#content").find('p.itemOldName');
$(objects).each(function(i, object){
console.log("*"+($(object).text()).toLowerCase() + "*" + name.toLowerCase()+"*");
if(($(object).text()).toLowerCase() == name.toLowerCase())
return true;
});
return false;
}
I am building an online file manager system.
the name argument is a name provided by the user via a textbox, and the $(object).text() is the name of files and folders in the current directory. These names come via exec("ls") command.
I need to check if the name provided by the user already exists. So I compare the name with every files/folders name. The problem is it doesn't find duplicates. The result of the above code is given in the following image
The return true returns out of the each callback. That has no effect on each (it only cares about return false) and doesn't do anything to set the return value of nameIsDuplicate.
You want to return false there (no need to keep looking) and set a flag so your nameIsDuplicate can return it:
function nameIsDuplicate(name){
var duplicate = false;
objects = $("#content").find('p.itemOldName');
$(objects).each(function(i, object){
console.log("*"+($(object).text()).toLowerCase() + "*" + name.toLowerCase()+"*");
if(($(object).text()).toLowerCase() == name.toLowerCase()) {
duplicate = true;
return false; // Stop looping
}
});
return duplicate;
}
However, that function can be a lot simpler using Array.prototype.some:
function nameIsDuplicate(name){
var objects = $("#content").find('p.itemOldName');
name = name.toLowerCase();
return objects.get().some(function(object) {
return $(object).text().toLowerCase() === name;
});
}
some calls its callback for each entry in the array. If the callback returns a falsy value, some keeps going; if the callback returns a truthy value, some stops. some's return value is true if a call to the callback returned a truthy value, false if not.
Your function doesn't return true, because you are in each loop... should be something like this:
function nameIsDuplicate(name){
var same=0;
objects = $("#content").find('p.itemOldName');
$(objects).each(function(i, object){
console.log("*"+($(object).text()).toLowerCase() + "*" + name.toLowerCase()+"*");
if(($(object).text()).toLowerCase() == name.toLowerCase()){
same=1;
return false;
}
});
if(same){
return true;
}else{
return false;
}
}
We can break the $.each() loop at a particular iteration by making the
callback function return false. Returning non-false is the same as a
continue statement in a for loop; it will skip immediately to the next
iteration.
Other solution:
function nameIsDuplicate(name){
return $("#content").find('p.itemOldName').filter(function(){return $(this).text().toLowerCase() === name.toLowerCase();}).length;
}
I call a javascript function from another as show below, but every time isPassword gets called, it returns as 'undefined' and not True or False as intended. I print the values before they get returned and they are correct, but return true; doesn't work still. Any ideas?
function isPassword(pass){
var datatosend = {};
datatosend['api'] = 'checkpassword';
datatosend['version'] = 'v1';
datatosend['pass'] = pass;
jsonAPI(datatosend,function()
{
if (typeof(responseVar['success'])=='boolean')
{
var ans = responseVar['success'];
if (ans)
{
//Returns true to changePassword();
return true;
}
else if (!ans)
{
//Returns false to changePassword();
return false;
}
}
});
}
function changePassword(){
//THE BELOW isPassword CALL IS UNDEFINED
if(isPassword(oldPass)){
successStatus.text("Current password not entered correctly");
successStatus.css('color', 'red');
clearTextAfter('changePasswordStatus', 5000);
return false
}
}
I can provide more code on request if it's more then a simple problem.
Not quite sure what jsonAPI is, but if it's an Ajax call, that's asynchronous, so the function itself ends after that function call (and there's no return value), while the anonymous function passed as an argument to jsonAPI will be executed a little bit later. You will need to do whatever you need with the response at that point, not when isPassword returns.
Im trying to is invoke function inside if statement only if it returns true. The below function checks the username field to make sure theres something in it if there is it sends it to the function validate form
function usernamecheck() {
if ($("#signupUsername").val().length < 4) {
return true;
}
}
function validateForm() {
if (usernamecheck(returns true)) {
//run code
}
}
Is it possible/ the best way to do it
function usernamecheck() {
//Updated this to just return the expression. It will return true or false.
return $("#signupUsername").val().length < 4;
}
function validateForm() {
//Here we just call the above function that will either return true or false.
//So by nature the if only executes if usernamecheck() returns true.
if (usernamecheck()) {
//Success..Username passed.
}
}
I have several functions in JavaScript whose results I want to use in an if statement in another function.
My problem is that only the first listed child function seems to be returning a result. When I swap the order of the functions around then I still only get a returning result from the child function listed first.
I'm a beginner and not all that familiar with functions just yet. See my example below. Please be specific with any answers.
function main(a) {
return functone(x); // name of function is actually "functone" for this example
return functtwo(y); // name of function is actually "functtwo" for this example
if(functone(x)!="true") {
return false;
} else {
if(functtwo(y)!="true) {
return false;
} else {
return true;
}
}
}
You can't return two values from one function. So your code should be
function main(a){
if(functone(x)!="true")
{return false;} else
{if(functtwo(y)!="true")
{return false;} else {return true;}
}
}
It appears that you want to only want to return true only if both of the called functions do.
A typical pattern for this would be:
function main(a) {
return functone(x) && functwo(y);
}
Note that in this case functwo will only be called if the result of funcone is false (or more strictly "falsey", i.e. also including null or 0) because the && operator is what's called a short circuit operator. If the result of the operation can be determined directly from the left hand operand, the right hand operand is not evaluated.
If you want functwo to be called regardless of the outcome of funcone then replace the && operator with the bitwise & operator.
Note that your funcXXX functions ought (like this function) to return the propert boolean value true or false, and not the string "true".