I am brand new to jQuery (and really javascript in general) and am trying to write a generic function that checks all text and select boxes on a page for input, returning 'true' if one or more boxes on the page contain at least one character and 'false' if not (the use is to disable a search button if there is no input). I've written the following function:
function hasUserProvidedInput() {
$('input[type="text"]').each(function() {
if ($(this).val() != '') {
alert("he has");
return true;
}
});
$('select').each(function() {
if ($(this).val() != '') {
return true;
}
});
return false;
}
The intent is that it will iterate through all textboxes and select boxes on the page, and the second it hits one with input it will return control to the calling function with a value of 'true' (I call the function with keyup events attached to textboxes and select boxes on the page). If it iterates through all these controls on the page and does not find one with input, it will return false.
I added the alert in for debugging purposes. The alert works properly to indicate when a textbox contains input, however my function always returns with a value of 'false'. Can anyone shed some light for me on why this is happening/how I can fix it? Thanks.
Where you're checking the val() of your inputs you are in the scope of an anonymous function. When you return a value from within one of those 2 anonymous functions that will just return from that function, not your overall hasUserProvidedInput function. So, essentially, the "return true" statements that you have in your anonymous functions are being discarded.
Try something like this:
function hasUserProvidedInput() {
var returnValue = false;
$('input[type="text"],select').each(function() {
if ($(this).val() != '') {
returnValue = true;
}
});
alert(returnValue);
return returnValue;
}
I put this code in a fiddle so you can play with it: http://jsfiddle.net/tddmp/
精彩评论