Reputation: 36726
I have this code to validate if a field is empty or not. It is binded into the blur event of a input with an anonymous function.
isValidText = function(){
if ($(this).val().trim() == ""){
//some code here
return false;
}
//some code here
return true;
}
$("#someElement").blur(isValidText);
At a certain point, I want to get the returning value from the binded function doing something like this:
//this return a jQuery object
var isValid = $("#someElement").blur();
//but I want the boolean from the isValidText
This is not possible because the blur()
method return a jQuery object and not the return value of the isValidText
function.
My question here is if there is a way to get the return value from the isValidText
binded inside the blur event.
Upvotes: 2
Views: 896
Reputation: 318302
I'd do it like this
var isValid;
isValidText = function(valueToCheck){
if ($.trim(valueToCheck) == ""){
//some code here
return false;
}
//some code here
return true;
}
$("#someElement").on('blur', function() {
isValid=isValidText(this.value);
//or just :
if (isValidText(this.value)) {
//do something
}
});
Upvotes: 1
Reputation: 87073
$("#someElement").blur(function() {
var ret = isValidText.call(this);
});
OR
$("#someElement").blur(function() {
var ret = isValidText.apply(this, arguments); // if you work with some hadler
});
Upvotes: 2
Reputation: 9031
You could use thecodeparadox solution, or you could add a HTML5 data attribute on your #someElement and look into that:
isValidText = function(){
var $this = $(this);
$this.data("isValid", !($this.val().trim() === ""));
}
$("#someElement").blur(isValidText);
/* Further down when you want to check if its valid or not */
if(!$("#someElement").data("isValid")) {
alert('someElement is not valid!') ;
}
Upvotes: 1