I have this function:
function RemoveProduct() {
if (confirm("Poista?") == return true) {
return true;
} else {
return false;
}
}
When you click a "remove" button on the page, it should ask if it should remove a product, and if the answer is yes, it will remove it.
But as far as I know, I can't use another brackets on the if sentence conditions?
How this should be done?
When you compare a return value to true you shouldn't use return true, just true:
function RemoveProduct() {
if (confirm("Poista?") == true) {
return true;
} else {
return false;
}
}
You don't even need to do the comparison, as the result from confirm is a boolean value:
function RemoveProduct() {
if (confirm("Poista?")) {
return true;
} else {
return false;
}
}
And you don't even need the if statement, you can just return the result from confirm:
function RemoveProduct() {
return confirm("Poista?");
}
Remember to use return when you use the function in an event. Example:
<input type="submit" onclick="return RemoveProduct();" />
confirm() returns a boolean value and you can return that. Like so:
function RemoveProduct() {
return confirm("Poista?");
}
But as far as I know, I can't use another brackets on the if sentence
conditions?
There is nothing that prevents you from executing a function within an if condition. That said, I always get all the arguments to my conditional settled before the if, for clarity and readability.
Here is your code greatly simplified.
var confirmed = confirm('whatever');
return confirmed;
just use
<a onclick="return confirm('ARe sure want to remove');">remove</a>
Related
How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
$("#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;
})
How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
I have a little question. I want to write a function in javascript and the function needs to take two extra parameters, for when the function is true and false. But I don't know how to write it. So, I want something like this:
function greater (para1, para2, casetrue, casefalse) {
if (para1 > para2) {
casetrue
}
else {
casefalse
}
}
Is this possible? Because I wrote that function and than I called the function with
greater(5,3, function() { return "is greater" }, function() { return "is smaller" }) and it didn't work.
Can anybody please help?
Thanks in advance
try this way, otherwise you'll be returning a function:
function greater (para1,para2,casetrue,casefalse) {
if (para1 > para2) {
return casetrue();
} else {
return casefalse();
}
}
To make the function greater return "is greater" or "is smaller" one must return the return value of the parameter functions:
function greater(para1, para2, casetrue, casefalse) {
return (para1 > para2) ? casetrue() : casefalse();
}
Tested on Firefox 24.0 / Linux
function greater (para1, para2, casetrue, casefalse) {
if (para1 > para2) {
return casetrue();
}
else {
return casefalse();
}
}
Like has been suggested in other answers, the greater function is returning functions instead of strings. If this is the desired behavior, you can call the returned function with an extra pair of brackets:
greater(5,3, function() {return "is greater"},function() {return "is smaller"})()
I want to use return false to break a .each() but also return a value at the same time. How can I do this?
Please refer to a work-around function to see what I am trying to do:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store) {
if (state == store.state && store.category == "meyers") {
statehasstores = true;
return false; // break
}
});
return statehasstores;
}
What Id like to do in pseudo code is:
Function () {
for() {
if found {
return true;
}
}
return false;
}
You're doing it right...
Quote from http://api.jquery.com/each/
"We can stop the loop from within the callback function by returning false."
Be creative:
try {
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
throw store;
}
});
}
catch(e) {
// you got e with the value
}
No, I was just kidding, don't use this :). It came as an idea I liked to share.
Use a variable outside the loop to get the value and use it afterward.
var value;
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
statehasstores = true;
value = store; // added line
return false; //break
}
});
alert(value);
The way you're doing is just fine. I've tested on jsFiddle, see an example here.
It's not working for you? Can you show more context?
jQuery .each
Alternatively, you could use a for loop instead of each(), and just return the value.
What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.
How about:
$.each( myObj, function( key, value ){
...
if( sthg... ){
myObj.somethingWentHorriblyWrong = true;
return false;
}
});
if( myObj.somethingWentHorriblyWrong ){
// ... do something, not forgetting to go:
delete myObj.somethingWentHorriblyWrong;
}
PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page, "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...
PPS Need a function that returns a value? Wrap in an outer function of course.
Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :
When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :
Function () {
for() {
if found {
return true;
}
}
return false;
}
This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.
So to make your function work as you whish I propose to do so :
Function () {
variable found = false;
foreach() {
if found {
found = true;
return false; // This statement doesn't make your function return false but just cut the loop
}
}
return found;
}
Of course there are many other ways to perform this but I think this is the simplest one.
Coopa - Easy !
As others have noted from jQuery Each, returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store){
// continue or break;
statehasstores = !(state == store.state && store.category == "meyers"))
return statehasstores;
});
return !statehasstores;
}
This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.