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
Related
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.
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;
}
I have a function, for example check navigator params, like that :
function paramsDevice() {
if ( navigator.userAgent. etc ... ) {
return true;
} else {
return false;
}
}
how to use the return, in a other part of js code ?
if (paramsDevice == false)
not working and i have no error
In your code you are comparing undefined variable paramsDevice with the boolean false.To compare returned by paramsDevice() value try the following :
if (paramsDevice() == false)
You can also assign a variable to the result to use it in the if statement :
var paramsDevice = paramsDevice()
if (paramsDevice == false)
use === to compare with false .You can assign your function a variable.Then you can check the variable if (paramsDevice == false)
var paramsDevice = function() {
if (1 === true) {
return true;
} else {
return false;
}
};
if (paramsDevice === false) {
alert('working....');
}
WORKING Demo
I have javascript with global variable declared:
var IsUserAllowed = false;
And I have a function:
function setSelectedIdsInput(inputLogicalId) {
if (IsUserAllowed) {
This does not work, I assume the value of IsUserAllowed is in string.
So i did:
var isUserAllowedStr = IsUserAllowed.toString().toLowerCase();
if (isUserAllowedStr == "true") {
This works, Since im new to java script i wanted to know if its ok to compare strings like this.
This due to fact that doing:
if (isUserAllowedStr.localeCompare("true")) {
Did not work either !
Thanks!
Update - i suspect the global var was string and not Boolean. this why the if failed. when i did alert(IsUserAllowed) the output was "False"
var IsUserAllowed = false;
then
function setSelectedIdsInput(inputLogicalId) {
if (IsUserAllowed) {
// something true
} else {
// something false
}
or
if(IsUserAllowed === true)
but it is useless.
Try:
if (isUserAllowed === true) {
}
isUserAllowed is a boolean (true / false):
You can check it by simply doing
if (isUserAllowed) { }
Or
if (isUserAllowed === true) { }
Your example should work as expected.
You can play around in this JSFiddle to test for yourself: http://jsfiddle.net/bT8hV/
var IsUserAllowed = false;
function setSelectedIdsInput() {
if (IsUserAllowed) {
alert('TRUE');
}
else {
alert('FALSE');
}
};
setSelectedIdsInput();
"return false;" for form submission is working for the rest of my code, just not this section. Any ideas why?
function checkForm() {
$("select[name*=lic_company]").each(function() {
if($(this).val() != '') {
var i1 = $(this).parent("td").next("td").children("select");
var i2 = i1.parent("td").next("td").children("input");
var i3 = i2.parent("td").next("td").children("input");
if(i1.val() == '') {
i1.parent("td").addClass("formErrorTD");
i1.addClass("formError");
alert("You must enter a state for this license");
return false;
}
if(i2.val() == '') {
i2.parent("td").addClass("formErrorTD");
i2.addClass("formError");
alert("You must enter an expiration date for this license");
return false;
}
if(i3.val() == '') {
i3.parent("td").addClass("formErrorTD");
i3.addClass("formError");
alert("You must enter a license number for this license");
return false;
}
}
});
}
and it's being called by
$("#addAgentForm").submit(checkForm);
You are calling return false; within a closure that is an argument passed to .each. Therefore, .each is capturing the return false;. To get around this you need need to have a boolean flag that holds the state of the form:
function checkForm() {
var okay = true;
$("select[name*=lic_company]").each(function() {
...
return okay = false;
...
});
return okay;
}
And everything will work fine.
Your return false statements are inside the anonymous function passed to .each(), so only return a value from that function, not the entire call to checkForm().
If I had to guess, it's because you're returning from the function passed to your each call, meaning all you're really doing is exiting your each function while your main validation function finishes without a hitch.