Click to See Complete Forum and Search --> : counting and validating textfields on page
damon2003
12-03-2003, 09:16 AM
Hi,
I create textfields on my page dynamically using PHP, so there could be 1 and upwards numbers of textfields. I need to validate each textfield to make sure it contains something.
Also I have checkboxes that can disable certain textfields, I dont want the disabled textfields to be validated, but I dont think disabled textfields get validated anyway do they?
thanks a lot
olerag
12-03-2003, 10:38 AM
In this example I've only used three fields. Regardless,
to make this work, the name of the checkboxes/text
fields must align and increment as you add new entries.
<html>
<head>
<script type="text/javascript">
function checkIt(form) {
var textObj;
var checkObj;
var errors = new Array();
var x = 0;
var str = "";
var temp;
for (var i=0; i<form.elements.length; i++) {
textObj = form.elements[i];
if (textObj.type == "text") {
temp = parseInt(textObj.name.substring(textObj.name.length-1,textObj.name.length));
checkObj = form.elements["check" + temp];
if (checkObj.checked) {
if (! textObj.value.length > 0) {
errors[x] = textObj.name;
x++;
}
}
}
}
if (errors.length > 0) {
for (var i=0; i<errors.length; i++) {
str = str + errors[i] + "\n";
}
alert("Validation Textfields:\n" + str);
}
else {
alert("Submit the form");
}
}
</script>
</head>
<body>
<center>
<b>Validation Example</b>
<form>
<table border="1" width="60%">
<tr>
<td><input type="checkbox" name="check1" value="Y">Check It</td>
<td align="center"><input type="text" name="text1" size="50" length="50"></td>
</tr>
<tr>
<td><input type="checkbox" name="check2" value="Y">Check It</td>
<td align="center"><input type="text" name="text2" size="50" length="50"></td>
</tr>
<tr>
<td><input type="checkbox" name="check3" value="Y">Check It</td>
<td align="center"><input type="text" name="text3" size="50" length="50"></td>
</tr>
</table
<br>
<input type="button" value="Submit" onClick="checkIt(this.form)">
</form>
</center>
</body>
</html>
Another way to do it is to "hide" the max amount of
text fields in a "hidden" and use this total to control the
interation in the JS function.