Jump to content

Parsing Form Elements


Greywacke

Recommended Posts

hi, i've got to write a javascript to parse all the elements of a form verifying that valid selections have been made. the form is created by zencart in php, and the fields vary accross the pages. this method does not seem to work, anybody able to help me in finding out why?

<script language="javascript" defer="defer"><!--function validateForm(form) {	for (i=0; i<form.elements.length; i++) {		if (form.elements[i].type != "checkbox" && form.elements[i].value == "") {			alert("Please fill out all fields.");			form.elements[i].focus();			return false;		}	}	return true;}document.cart_quantity.onsubmit = new function () {	return validateForm(this);}//--></script>

this piece of code is in the template form generator, after closing the form.in IE i get an error trying to parse the elements array like this, what am i doing wrong?in firefox i get no errors, but the form submits empty. i'm assuming the other 3 standards compliant browsers are also like this (chrome, opera and safari).

Webpage error detailsUser Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET CLR 1.1.4322)Timestamp: Fri, 29 Jan 2010 13:15:53 UTCMessage: 'elements.length' is null or not an objectLine: 573Char: 12Code: 0URI: http://canopyxchange.za.net/index.php?main...products_id=159
even pointing me in the right direction would be helpful, thanks.
Link to comment
Share on other sites

document.cart_quantity.onsubmit = new function () {This line is a problem. The word new thinks you are constructing an object, so it runs validateForm when the script runs and assigns the return value of the anonymous function to onsubmit. Then validateForm is never called again.Just remove the word new and go from there.I have to add that putting up an alert for every error is bad user interface. It's fine for testing, but I urge you to find a better solution for your release version. Try not to halt the response every time you find an error. Let the errors accumulate before you do something with them. At the very least, concatenate a single string while you loop through ALL the form elements, and then alert the string.

Link to comment
Share on other sites

thanks for the help DD :)one more question... if you have a look at the form, it's got a label tag for each field. is there any way to access this?here is the current code. unfortunately it can only be done this way, the validation has to be clientside. it goes through the elements till it finds a problem, then stops and focuses on the field before cancelling the submit if it found an invalid field.

<script language="javascript"><!--function validateForm(form) {	var strFilter = /^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i;	for (i=0; i<form.elements.length; i++) {		var elm = form.elements[i];		if (elm.type != "checkbox" && // check noncheckbox elements		  ((elm.name == "attrib-22-0" &&		  (!strFilter.test(elm.value) || elm.value == "")) || // check invalid emails		  elm.value == "" ||  // check other fields		  elm.value == "210" || elm.value == "217" || // check invalid selections		  elm.value == "218" || elm.value == "153")) {			alert("Please fill out all fields correctly.");			elm.focus();			return false;		}	}	return true;}document.cart_quantity.onsubmit = function () {	return validateForm(this);}//--></script>

how would i be able to reference the labels for each element item to get the displayed name? they are for each element id. here is an example of the generated form:

<div class="wrapperAttribsOptions"><h4 class="optionName back"><label class="attribsSelect" for="attrib-1">Colour code :</label></h4><div class="back"><select name="id[1]" id="attrib-1">  <option value="37">Tonic</option>  <option value="38">Satin White</option>  <option value="40">Colorado Red</option>  <option value="64">Ocean Blue</option>  <option value="41">Pure Silver</option>  <option value="65">Plum Blush</option>  <option value="43">Black Sapphire</option>  <option value="66">Titanium Grey</option>  <option value="45">Oyster Silver</option>  <option value="12" selected="selected">White Non-coded (standard)</option></select></div>

Link to comment
Share on other sites

I understand that your validation is clientside, and what I suggested can all be done clientside. My suggestion is intended to keep your users from being extremely annoyed. If you don't want to mess with it, fine.You can certainly associate your label with your element, because the for and id attributes match. But it will require another interior loop. We could do that.But it would be a LOT easier if you made a few simple changes to your HTML.<h4 class="optionName back"><label class="attribsSelect" for="attrib-1">Colour code :</label></h4>I see no reason the h4 attributes could not be combined with the label attributes. Then you could just have a label element.Then, if you could put the label inside the div called "back" instead of before it, the select element and the label would have the same parent node. This would make the following line of code possible:mylabel = elm.parentNode.getElementsByTagName("label")[0];and that would be very simple indeed.

Link to comment
Share on other sites

success!!!seems i need to replace the odd & with & to get this code to work. names derived from the individual labels.

<script language="javascript"><!--var labels = document.getElementsByTagName('LABEL');for (var i = 0; i < labels.length; i++) {    if (labels[i].htmlFor != '') {         var elem = document.getElementById(labels[i].htmlFor);         if (elem) elem.label = labels[i];    }}function validateForm(form) {	var strFilter = /^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i;	for (i=0; i<form.elements.length; i++) {		var elm = form.elements[i];		var val = elm.value;		var tx = elm.label.innerHTML.replace(" :","").replace(/&/,"&");	// get the label to alert		if (			elm.type != "checkbox" &&					// not a checkbox and			(								// (			(elm.name == "attrib-22-0" && !strFilter.test(val)) ||		// (email field and invalid email)			val == "" ||							// empty field value or			val == "210" || val == "217" || val == "218" || val == "153"	// invalid dropdown options			)								// )		   ) {				alert("Please fill out "+tx+" correctly.");				elm.focus();				return false;		}	}	return true;}document.cart_quantity.onsubmit = function () {	return validateForm(this);}//--></script>

as i have said before, DD - unfortunately i have to work with what i have got here... the validation will not pop up a warning if the fields have valid selections / e-mail addresses. i just hope this if statement should check on emails. the live script can be seen on http://canopyxchange.za.net/index.php?main...products_id=146 or any other specific canopy product.unfortunately, javascript cannot focus on all the elements with invalid selections / values all at once, so i would rather do it this way. its to prevent invalid data from entering the database, thus invalid leads being generated.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...