jQuery – Validate all inputs within a DIV (Incomplete)

I am looking to validate all inputs within a DIV to make sure they are not empty. I was able to get some code to work that can loop through elements, alert when empty and focus. But I had a problem returning from the callback function and the code would jump through to the next statement and validate it, whereas it is not required.

$( '#id_div_eval_container' ).find('input[type="text"]').each(function () {
	//alert(this.name); // "this" is the current element in the loop
	//alert(this.value);
	if(this.value.trim() == "") {
		alert("Enter valid value for Eval data");
		this.focus();
		//return false;	//-- Not working
	}
	return true;	//-- Not working
});
alert("Should never reach here. Must return from failure above");

If you happen to read this and know a resolution, please feel free to share :). For time being, I’m using a temporary validation by representing elements in an array.

//-- Gets called on form submit
function validateForm() {
	var arr_evalFieldNames = ["eval|company", "eval|first_name", "eval|last_name", "eval|email"];
	if (!validateMandatoryElements(arr_evalFieldNames)) {
		return false;
	}
}
//-- Accept array of field names and return false if either one of them is blank
function validateMandatoryElements(arr_fieldNames) {
	for (index = 0; index < arr_fieldNames.length; ++index) {
		$element = $( '[name="'+arr_fieldNames[index]+'"]' );
		if ($element.val().trim() == "") {
			alert("Enter valid valid value for Eval data");
			$element.focus();
			return false;
		}
	}
	return true;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s