Difference between JQuery $.each loop and JS for loop [duplicate] - javascript

I want to return false and return from function if I find first blank textbox
function validate(){
$('input[type=text]').each(function(){
if($(this).val() == "")
return false;
});
}
and above code is not working for me :(
can anybody help?

You are jumping out, but from the inner loop, I would instead use a selector for your specific "no value" check, like this:
function validate(){
if($('input[type=text][value=""]').length) return false;
}
Or, set the result as you go inside the loop, and return that result from the outer loop:
function validate() {
var valid = true;
$('input[type=text]').each(function(){
if($(this).val() == "") //or a more complex check here
return valid = false;
});
return valid;
}

You can do it like this:
function validate(){
var rv = true;
$('input[type=text]').each(function(){
if($(this).val() == "") {
rv = false; // Set flag
return false; // Stop iterating
}
});
return rv;
}
That assumes you want to return true if you don't find it.
You may find that this is one of those sitautions where you don't want to use each at all:
function validate(){
var inputs = $('input[type=text]');
var index;
while (index = inputs.length - 1; index >= 0; --index) {
if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
return false;
}
}
// (Presumably return something here, though you weren't in your example)
}

I want to add something to existing answers to clear the behavior of $(selector).each and why it doesn't respect return false in OP's code.
return keyword inside $(selector).each is used to break or continue the loop. If you use return false, it is equivalent to a break statement inside a for/while loop. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. Source
Because you're returning false, the loop breaks and the function ends up returning undefined in your case.
Your option is to use a var outside $.each or avoid using it altogether as #TJCrowder wrote.

Related

Why wont my function return true?

I cant seem to get this function to return true even after ticking the two check boxes I have on the page. I've been working on this for hours now and running out of ideas. Any help would be much appreciated.
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
if($("input[type=checkbox]").length > 0){
$('.checkbox').each(function(){
if($(this).prop('checked')){
return true;
}
else{
$(this).find(".CheckboxCheck").show();
return false;
}
});
}
else{
return true;
}
}
You are returning true from within the function that you passed to each, not from myfunction. Except in the case that there are no check boxes on your page, and thus the else block executes in myfunction, myfunction is returning undefined.
You can do something like this however:
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
var returnValue = true;
if($("input[type=checkbox]").length > 0) {
$('.checkbox').each(function(){
if($(this).prop('checked')){
returnValue = true;
return false; // Stops the each loop.
}
else {
$(this).find(".CheckboxCheck").show();
returnValue = false;
return false; // Stops the each loop.
}
});
}
return returnValue;
}
Now, I'm not exactly sure of what you're trying to do, and you will almost certainly need to tweak the code above. I'm just providing it as a way to illustrate how to get a value out of the function passed to each. If you're trying to determine if all of the checkboxes are checked, for example, then you'll want your each function to look something like this:
var returnValue = true;
...
$('.checkbox').each(function() {
if (!$(this).prop('checked')) {
returnValue = false;
return false;
}
});
EDIT: After looking at the second code snippet again, I realized that the each loop is unnecessary. If you want to determine if all check boxes are checked, all you need is this:
if ($('.checkbox:not(:checked)').length == 0) {
// All .checkbox elements are checked.
}
Now, keep in mind that the :not() and :checked selectors can't utilize the native JS functions, so they are slower, but probably not enough to matter. I prefer the conciseness.
Returning from inside the each callback function will not return from the outer function. The function will return undefined as you haven't specified any return value for it, and that is not equal to true.
You can use a variable for the result, that you set from within the loop:
function myfunction(){
var result = true;
$('.checkbox').each(function(){
if(!$(this).prop('checked')){
result = false;
$(this).find(".CheckboxCheck").show();
return false; // exit the loop
}
});
return result;
}

Javascript function returning undefined for template helper

Creating a template helper to return a variable to be displayed in the DOM, and my function is returning undefined and thus is not affecting the DOM. Not exactly sure why, though I feel as if it is a binding issue. Here's the code:
supportNumber: function(){
var jobSupportNumber = state.user.jobs.each(function(job){
console.log(jobOrder.get("jobId"));
console.log("test");
console.log(job.get("id"));
if(jobOrder.get("jobId") == job.get("id")){
var jobNumber = job.get("supportNumber");
console.log(jobNumber);
return jobNumber;
}
else{
console.log("this fired");
}
});
console.log(jobSupportNumber);
return jobSupportNumber;
}
I'm console logging alot to make sure values are being returned, and something is being returned all the way up until the final return statement, which returns jobSupportNumber as undefined. What am I doing wrong to have it return always as undefined?
.each() doesn't return the value of any of the function it's wrapping. The inner function results are only used to control the .each() loop.
Try this:
supportNumber: function(){
var jobSupportNumber = null;
state.user.jobs.each(function(job){
if(jobOrder.get("jobId") == job.get("id")){
jobSupportNumber = job.get("supportNumber");
return false; // tell .each() to quit looping
}
});
return jobSupportNumber;
}
By the code you have there, state.user.jobs.each() is not going to return jobNumber. That return applies to your anonymous function. (where you have function(job).
To get that value, you want something more like this:
supportNumber: function(){
var jobSupportNumber;
state.user.jobs.each(function(job){
console.log(jobOrder.get("jobId"));
console.log("test");
console.log(job.get("id"));
if(jobOrder.get("jobId") == job.get("id")){
var jobNumber = job.get("supportNumber");
console.log(jobNumber);
/* Set the value and just plain return, instead */
jobSupportNumber = jobNumber;
return;
}
else{
console.log("this fired");
}
});
console.log(jobSupportNumber);
return jobSupportNumber;
}

Exit from a javascript function

I saw many places similar question but couldn't fix it.
Here's my function:
function validate_form(){
$('#form_data input[type="text"]').each(function(){
value = $(this).val().trim();
if(value != '' && value != null && value != 0 ){
return true;
}
});
return false;
}
Its not exiting on return true;. I have also tried e.preventDefault() but no use.
return will return from the function it is in. In your code, that is the anonymous function you pass to each. See the documentation for each:
You can stop the loop from within the callback function by returning false.
You are returning true, not false so you aren't stopping the loop. Change true to false on line 5 of the function.
function validate_form(){
$texts=$('#form_data input[type="text"]'); //cache the object
var len = $texts.length;
var validItems=0;
$texts.each(function(){
value = $(this).val().trim();
if(value === ''){ // value of a text input cannot be null
// or zero unless you've changed in with JS
return false;
}
validItems++;
});
return len===validItems;
}
The function doesn't exactly show what item is invalid, just returns false if any of the items is invalid.
You have to let the .each() finish before you return from the main function body. You can keep a counter of valid entries you have come across and let the return value depend on that:
function validate_form()
{
var items = $('#form_data input[type="text"]'),
count = items.length,
valid = 0;
items.each(function() {
value = $(this).val().trim();
if (value != '' && value != null && value != 0 ) {
++valid;
}
});
return valid !== count;
}
Btw, I've changed the return value to false if there's at least one invalid entry; assuming you're using this as onsubmit="return validate_form()".

Avoid execution goes on in a .each loop

I've got a code like this one to see whether some radio buttons have been checked or not. I'm using .each function of jquery to show an alert when I find a group of radio buttons with the same name value and none of them have been checked. When I find one I want to fire an alert and return false, but after the alert is shown the execution of the .each stops but the lines after .each function are executed (I mean true value is executed).
$(":radio").each(function(){
var name = $(this).attr('name');
var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
var notAnswered = numAnswered == 0;
if(notAnswered){
alert("Must answer all questions");
return false;
}
});
console.log('still goes here even when alert is fired');
return true;
How can I avoid this situation?
Thanks.
var myreturnvalue = true;
$(":radio").each(function(){
var name = $(this).attr('name');
var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
var notAnswered = numAnswered == 0;
if(notAnswered){
alert("Must answer all questions");
myreturnvalue = false;
return false;
}
});
console.log('still goes here even when alert is fired');
return myreturnvalue;
You can use that same notAnswered variable (or another, whatever floats your boat) at a higher scope, like this:
var notAnswered;
$(":radio").each(function(){
notAnswered = $(":radio[name="+this.name+"]:checked").length == 0;
if(notAnswered){
alert("Must answer all questions");
return false;
}
});
if(notAnswered) return false;
console.log("will only fire if there's an answer");
return true;
The other changes above are just slimming down the code, you can get away with far fewer selector engine invocations :)

Return from inner function in JavaScript?

I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.
required_fields.forEach(function(field) {
if (field.val() == '')
{
field.addClass('field-highlight');
return false;
}
else
{
field.removeClass('field-highlight');
}
});
// I want to return to here from the return false point
How can I structure this differently to do what I want?
Just use a variable to keep track of the validation:
var is_valid = true;
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
is_valid = false;
return false;
} else {
field.removeClass('field-highlight');
}
});
return is_valid;
Or, you can just use the field-highlight class as well:
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
return false;
} else {
field.removeClass('field-highlight');
}
});
return $('.field-highlight').length == 0;
use a boolean in the forEach closure, which would be set to true, if the field value is empty. Check that value before submission of form
It sounds like you want to do the following
Update the elements with the field-highlight class based on whether or not they have a value
Block the form submission if any are empty
If so then try the following
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
Did you write the "forEach" function? If so, that could check the return value of the anon function, and if it is ever false, stop iterating.
If your required_fields is a jQuery object, you could just do this:
var stop = required_fields.removeClass('field-highlight')
.filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
Or perhaps more efficient like this?
var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
.end().filter("[value == '']").addClass('field-highlight')
.length;
return !!stop

Categories

Resources