Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Submit form inputs ONLY if they containing text 1

Status
Not open for further replies.

Akumadevil

Programmer
Sep 25, 2005
9
AU
Hi,

I have a very large form with about 1000 input fields, most of which stay empty. On submit it transfers around 150kB (about 20kB is actually user input).

Is there a way to only submit the form elements that are not empty?

Cheers.
 
Make a onsubmit handler within which get the collection of form's elements. Check out those elements of type "text" and see if they are empty or not. If anyone of them is found empty, return false forbidding the form to submit.
[tt]
function onsubmithandler(obj) {
var celem=obj.elements;
for (var i=0;i<celem.length;i++) {
if (celem.type=="text") {
if (celem.value=="") {
//some alert message if you like
celem.focus();
return false;
}
}
return true;
}
[/tt]
Call it like this.
[tt] <form onsubmit="onsubmithandler(this)">
[/tt]
 
If you only want to submit non-empty text inputs, you should set them to disabled if they are empty. You can do this with an onsubmit handler:

Code:
<form onsubmit="onsubmithandler(this);">

and the code:

Code:
function onsubmithandler(frm) {
	var els = frm.elements;
	for (var loop=0; loop<els.length; loop++) {
		if (els[loop].type.toLowerCase() == 'text') {
			if (els[loop].value == '') els[loop].disabled = true;
		}
	}
}

If you want to ensure that text inputs with only whitespace in are also ignored, then use this instead:

Code:
// removes all whitespace from the start and end of a string
function stringTrim(strToTrim) {
	return(strToTrim.replace(/^\s+|\s+$/g, ''));
}

function onsubmithandler(frm) {
	var els = frm.elements;
	for (var loop=0; loop<els.length; loop++) {
		if (els[loop].type.toLowerCase() == 'text') {
			if (stringTrim(els[loop].value) == '') els[loop].disabled = true;
		}
	}
}

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top