Consider this code:
function reason(id) {
var reason = prompt("State reason");
while (!reason.trim()) {
reason = prompt("Please enter text");
}
document.getElementById(id).value = reason;
return true;
}
It works perfectly fine, but when I want to get rid of the poppup by pressing escape for example, the function returns true because the form executes. What should I do to make it do nothing if I close/cancel the poppup?
... the function returns true because the form executes. What should I do to make it do nothing if I close/cancel the poppup?
It depends entirely on how you call your reason function, but if you want reason to return false when prompt is cancelled, then:
function reason(id) {
var reason = prompt("State reason");
while (reason !== null && !reason.trim()) { // *** Changed
reason = prompt("Please enter text");
}
if (reason === null) { // *** Added
return false; // *** Added
} // *** Added
document.getElementById(id).value = reason;
return true;
}
prompt returns null when you cancel it.
But again, it's up to what calls reason to do something appropriate with the true or false.
Side note: You can call your function and a variable inside it by the same name, but it's not a great idea. If it's a habit, you'll end up making writing recursive functions quite difficult...
Related
so i want to stop the code when a certain event happens but dont want to use return since the function is supposed to return a value and if i use it to stop the code it would reutnr an undefined value
for example this what i need
foo =() =>{
if(event){
//stop code
}else {
return "Value"
}
}
what i dont want to do
bar =() =>{
if(event){
// dont want to use it since it would return an undefined value
return ;
}else{
return "Value" ;
}
}
But why would you not want undefined to be returned? I mean... even if you have a function that returns no value at all it would still return undefined.
const a = (function(){})();
console.log(a); // undefined
This is just default behaviour of javascript. However, if you wish to stop execution due to a certain condition my best suggestion to you is to throw an exception and handle it.
const MyFunction = (b) => {
if (b) throw 'You shall not pass!';
return 'I shall pass! This time...';
};
try {
console.log(MyFunction(false));
console.log(MyFunction(true));
} catch(err) {
console.log(err);
}
I have an object which stores department hierarchy. Each department might have sub department as well. I am trying to loop to check all department and also sub(child) department properties are Open.
However, whenever I hit recursive call, it only iterates once and jump directly to return true, even though there are still some items which has not checked in the loop yet.
validateDepartment(departmentHierarchy: any) {
for (let dept of departmentHierarchy.children) {
if (dept!= undefined && dept!= null) {
if (dept.instance.status == "Open")
{
continue
}
else
{
if (dept.children != undefined && dept.children != null) {
this.validateDepartment(dept);
}
else {
return false
}
}
}
}
return true
}
Not part of any answer, but it helps to only write the code that "does" things, rather than having lots of code that does "what the code would already do anyway", such as calling a continue when the iteration code is a single if/else. We can rewrite your code to this, and have something easier to work with:
validateDepartment(tree: any) {
// step 1: do any validation of the top node
if (!validateTopNodeOnly(tree)) {
// this is a stop condition.
return false;
}
if (!tree.children) {
// this is also a stop condition, but for a different reason.
// a department without children should not _necessarily_ be invalid.
return true? return false? probably return true since the node itself is fine.
}
if (tree.instance && tree.instance.status !== "open") {
// and this is a third condition, but for yet another reason.
// I'm guessing this is also not "invalid", just means we shouldn't recurse.
return true? return false? probably return true as well.
}
// Then, get all (non-falsey) children,
let children = tree.children.filter(e => e);
// and iterate over them:
for (let e of children) {
let result = this.validateDepartment(e);
// cut your run short if validation fails
if (result === false) {
return false;
}
}
// and this is the expected stop condition for a normal run.
return true;
}
But using true/false is incredibly naive and won't tell you anything about where validation failed, so you'll want to work in "what failed", typically by returning a reference to the actual "thing that's getting validated" so that if your function returns true, all is well, and it returns something !== true then you know it failed, and the thing it returned is the department where things went wrong.
Also note that by using an early return on validation failure, you're missing out on information: instead it's way better to use .map() and construct a running tally of all deparments that pass/fail validation, so that you return an array in which either result.every(e => (e===true)) is true, or is false, in which case result.filter(e => (e!==true)) gives you the set of every single failed department.
isopen = this.validateDepartment(this.departmentHierarchy);
validateDepartment(dept: any): boolean {
let result=(dept.instance.status == "Open");
if (result) {
if (dept.children) {
dept.children.forEach(x => {
result = result && this.validateDepartment(x)
})
}
}
return result;
}
$("#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;
})
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.
I have this function:
function kontrola(){
var jmeno = self.document.forms.newPassForm.user.value;
$.get("checkMail.php?mail="+jmeno, function(data){
if(data=='1'){
alert('Tento uživatel v databázi neexistuje!');
return false;
}else return true;
});
}
My problem now is, that alert is not displaying (value for data variable is passed ok). If I add return false; at the end of the function, the alert is displayed, but if condition isnt fullfilled, I can´t send data from the form. Do you have any solution for this?
return does not do the same thing in a jQuery callback as it would in a normal function.
jQuery views return true; as continue (and assumes that you just wanted to skip to the next object in the jQuery object's set) and return false; as break (and assumes you just want to break out of the current iteration). return false when used in some event handlers will also prevent the default event behavior, but it is not the recommended approach to do that.
A better way to accomplish getting the return value would be to "split" your calling function with a callback that you inject into the get call.
function kontrola(callback){
var jmeno = self.document.forms.newPassForm.user.value;
$.get("checkMail.php?mail="+jmeno, function(data){
if(data=='1'){
alert('Tento uživatel v databázi neexistuje!');
callback(false);
}else{ callback(true); }
});
}
function someCaller(){
var someWork = 1 + 2;
//split the rest of this call function to be done inside of the callback
kontrola(function(result){
var boolResult = result;
if( boolResult ){
//do more work
}else{
//handle false case
}
});
}
edit
Since this is attached to a submit button, I would suggest sending the submit element with the event
onsubmit = return "kontrola(this);"
For the reason that you are going to submit at a later time if successful
function kontrola(submitElement){
var jmeno = self.document.forms.newPassForm.user.value;
$.get("checkMail.php?mail="+jmeno, function(data){
if(data=='1'){
alert('Tento uživatel v databázi neexistuje!');
}else{ submitElement.submit(); }
});
return false;
}
If you data variable is an integer, you will want data===1 without those currently present single quotes (which compares to a string, which will always fail when comparing to a number).