So, i'm trying to take a jQuery var and use it as a rule for the .validate plugin.
The var comes from a function that runs a function and give 1 for true and 0 for false, the problem is that i can't make the rule return true or false for the validate function. The code reads:
$.validator.addMethod("cpfc", function(){
if (($(CPF.valida($(cpf).val())).size()) === '1' )
{
return true;
}
else
{
return false;
}
});
$(CPF.valida($(cpf).val())).size() = 1 or 0, depends on the function check, I ran this function on the console and it's returning the correct values.
Any help will be appreciated
You have a semi-colon between the if and else statement which will be causing a syntax error. Also note that size() (aside from being deprecated) returns an integer, so your current code will always return false as you compare it to a string. It's now recommended to use the length property instead:
$.validator.addMethod("cpfc", function(){
if ($(CPF.valida($(cpf).val())).length === 1) {
return true
} else {
return false
}
});
This can be further reduced to just
$.validator.addMethod("cpfc", function(){
return $(CPF.valida($(cpf).val())).length === 1;
});
You should also ensure that the CPF object and cpf variable are in scope and hold the values you expect when called from within the validator method.
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.
This question already has an answer here:
How to write a function using the built-in local variable arguments?
(1 answer)
Closed 4 years ago.
I am supposed to finish the provided function 'climb' shown below. Using the built-in local variable arguments, within the function climb.
This is what the function is to do :
If there is a string at arguments[0] but arguments[1] is falsy, return "On belay?".
If there is a string at arguments[0], and true at arguments[1],
return "Climbing!"
Otherwise, return "Let's set up the belay rope before we climb."
Has to pass these tests:
should be a function that does not have built-in parameters
should return "Let's set up the belay rope before we climb." if called as climb()
should return "Climbing!" if called with climb("Benny", true)
should return "Climbing!" if called with climb("any string here", true)
should return "On belay?" if called with climb("Benny", false)
should return "On belay?" if called with climb("any string here")
Here is the provided function:
function climb(){
//CODE HERE - DO NOT TOUCH THE CODE ABOVE!
}
This is what I am trying and it doesn't work:
function climb(){
//CODE HERE - DO NOT TOUCH THE CODE ABOVE!
if(arguments[0]){
if(arguments[1]==false){
return "On belay?";
} else {
return "Climbing!";
}
} else {
return "Let's set up the belay rope before we climb.";
}
}
If I understand you correctly, your function needs to work based on local variables, not input arguments.
That being said, your comparisons don't make much sense.
E.g. arguments[0] == arguments[0] should always return true, as it is being compared to itself.
Try something like
//check that arg[0] has a value (assuming it is a string)
if(arguments[0]){
if(arguments[1]==false){
return "On belay?";
} else { //arguments[1] == false is implicit here
return "Climbing";
}
} else {
return "Let's set up the belay rope before we climb.";
}
Also take note of the difference between != (not equal) and !== (not equal value or not equal type).
arguments[0] == arguments[0] is always going to be true because you are checking if it is equal to itself. Also to check if an element is true you just do if(element) You code should instead look like this:
if(arguments[0] != '') {
if(arguments[1]){
return "On belay?";
}
else {
return "Climbing";
}
} else {
return "Let's set up the belay rope before we climb."
}
if(arguments[0]==arguments[0]) will forever be true no matter what arguments[0] is.
To check if arguments[0] has a string you can use typeof and length.
if(typeof arguments[0] === "string" && arguments[0]+"".length){
//runs this, if arguments[0] is a string with data in it.
}
this will check if it is a string and if it has anything in it.
To check if arguments[1] is false you could use if(!arguments[1]) but then will still run true if arguments[1] is undefined or an empty string.
I would suggest using a more readable and secure way.
if(arguments[1]===false){
//runs this, if arguments[1] is false
}
This question already has answers here:
How to check if a value is not null and not empty string in JS
(11 answers)
Closed 4 years ago.
I have the following html, which is part of a webform:
<input type="hidden" name="userID" id="control_COLUMN43" value="%%userID%%">
The value of this field is dynamically generated by a database. It's possible that the value of this field is empty.
Next to this, I created a function which sends the value of this field (via Ajax) to another database, upon a submit of the webform.
What I want to do now is: only execute this function if the value of the field "userID" is NOT empty. If it's empty, I don't want this function to be executed.
So I assume it will be something like this, but I'm struggling to find the correct way to do this:
if (#control_COLUMN43 !=== "") //this is the id of the field
{
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
Or the other way around I guess?
Can anybody help me with this?
Thanks in advance!
Use like this
// Also u can add null check
if(data !== '') {
// do something
}
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
You should not declare functions inside the conditions. If you do then at the time of execution if the condition is not met, function will not be available which may lead to errors. Hence, you should place the condition inside the function.
You can modify your condition to following
function SendAjax() {
if (document.getEelementById("control_COLUMN43").value) {
//code
}
}
You can access the value of the input by using getElementById(id).value
and declare your function outside the if block like:
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
if (document.getElementById('txt_name').value) //this is the id of the field
{
SendAjax()
}
else
{
//don't execute function
}
The if statement you need, without JQuery, should be like this:
if (document.getElementById("control_COLUMN43").value !=== "") {
// .. commands
}
First get your hidden input value using document.getElementById() and then check if it is null like following:
var userId = document.getElementById("control_COLUMN43");
if (userId) //this is the id of the field
{
SendAjax()
}
else
{
alert("UserId is null);
}
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
In if condition check $("#control_COLUMN43").val()
It can be null or '' so you can apply condition accordingly.
You can check empty value like this
function isEmpty(str) {
return (!str || 0 === str.length);
}
var val = document.getElementById('control_COLUMN43').value;
var col = isEmpty(val);
if (col) {
function SendAjax(){
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
There are several issues at once:
You are mixing up declaring a function with calling it.
To get the value from a control, use document.getElementById("...").value
The proper notation for not === is !==.
This is how it goes:
// Declare the function
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
// Get value
var value = document.getElementById("control_COLUMN43").value;
// Call the function conditionally
if (value !== "")
{
SendAjax();
}
The code you write in if condition is not correct ID value must be get like:
if(document.getElementById("control_COLUMN43").value != ''){
//Your code here
}
Basically you have to check value property of the input element. Using dom selectors first you can select a element using id then you can access value attribute for element. If it's not null or undefined or just empty spaces then you can call your function
function handleClick(){
// Extract value from input element
let val = document.getElementById('input').value;
// Check value is empty or not
if(val){
// If not empty
console.log('Value is : ' + val);
}
else{
// If empty
console.log('Empty input');
}
}
<input id="input" type="text">
<button onclick="handleClick()">SUBMIT</button>
// get the contents of the form element
var control_COLUMN43 = document.getElementById("control_COLUMN43").value;
// process the data
if( control_COLUMN43 != "" ) {......
I seem to be lost or just seem to be confused.
To simplify the problem: I want to check whether each in an array holds true and if and only if all are true it should return a specific value.
var trueArray=[true,true,true,true];
As in my code, the array can have length up to 100 elements, I can't simply check for every element but need a for loop.
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===true)
{
//do something
}
}
However, the above code does something on each step of the loop but I only want it to do something once every condition held true and not in between. Can't think of the solution at the moment?
Use Array.prototype.every
if (trueArray.every(function(x) { return x; })) {
//do something
}
If it's guaranteed to be a boolean you can check if any of them are false instead of if they're all true with Array.prototype.indexOf
if(trueArray.indexOf(false) === -1) {
// none are false, so do stuff
}
You wouldn't need to use a loop or create a function.
Declare a check variable who is already true and set it to false if one of your array values is false. After that, check if it's true and do something.
Example:
var trueArray=[true,true,true,true];
var bCheckArrayVal = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
bCheckArrayVal = false;
}
if (bCheckArrayVal) {
// do something if true
} else {
// do something if false
}
}
Try the following code:
var currentValue = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
currentValue = false;
}
}
if(currentValue === true){
//do something
}
You should short circuit the logic as soon as you get a false value, must answers are not getting your question because of the misleading logic you put inside the for even though you only want it done once if all values are true.
You need something like
var flag=true;
for(var i =0;i
if (flag) { do something}
You can do it like this...
var trueArray=[true, true, true, true];
var allTrue=false;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
allTrue=false;
break;
}
else
{
allTrue=true;
}
}
if(allTrue==true)
{
// do something if all values are true
}
You must break the loop if the false value is detected.
I have a checkboxall and checkbox group.When I click the checkboxall, all the checkbox group will be checked.When I make all the checkbox group checked,the checkboxall will be checked.I write the codes like these,but my parner say that add return false will be better.It is right?I find that add return true or return is also well.How about break?
$("#CheckedAll").click(function(){
if(this.checked){
$('input[type=checkbox][name=items]').attr("checked", true );
}else{
$('input[type=checkbox][name=items]').attr("checked", false );
}
});
$('input[type=checkbox][name=items]').click(function(){
var flag=true;
$('input[type=checkbox][name=items]').each(function(){
if(!this.checked){
flag = false;
return false; //return;return true,break;?
}
});
if( flag ){
$('#CheckedAll').attr('checked', true );
}else{
$('#CheckedAll').attr('checked', false );
}
});
When you're using jQuery each - you want to return false only when you want to stop the loop.
Neither return / return true would stop the loop from iterating.
var a=[1,2,3,4,5];
$.each(a,function (i,n){
if (n==2) return;
console.log(n)
})
result = 1,3,4,5
$.each(a,function (i,n){
if (n==2) return true;
console.log(n)
})
result = 1,3,4,5
$.each(a,function (i,n){
if (n==2) return false;
console.log(n)
})
result = 1
$.each(a,function (i,n){
if (n==2) break;
console.log(n)
})
result : Uncaught SyntaxError: Illegal break statement
Your colleague is right: once you find one instance of a checked checkbox, there's no point in continuing the loop. return false stops the each loop from iterating. break won't do anything because .each() is not a native loop and returning something other than false will stop the current iteration but not the entire loop.
That said, you can avoid the each loop entirely and simplify the code considerably. Also, you need to use .prop() instead of .attr(). Try this:
$("#CheckedAll").click(function () {
$('input[type=checkbox][name=items]').prop("checked", this.checked);
});
$('input[type=checkbox][name=items]').click(function () {
$('#CheckedAll').prop(
'checked',
$('input[type=checkbox][name=items]:not(:checked)').length === 0
);
});
demo
"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."
It depends on your intentions. If you need to stop looping, return false. Otherwise, you do not need to return anything given your provided code.
http://api.jquery.com/jquery.each/
jQuery doesn't allow "break" keyword like in many other programming languages.
neither returning true will sneak you out of the loop.
so to get the behavior of break statement with jQuery, better you return false.
for the equivalent output.