...

View Full Version : Problem with combo boxes



hendryk
07-26-2002, 06:08 PM
Hi,

This function works fine except when the form field is a combo box. When one of the options is selected it still gives the error message "....this is a required field. Please enter a value."

What is going on?

K


function validateFields (aform)
{ var fieldArray =["hospUnitNo","gp","bwt","workingDiagnosis"];

var userNames = ["Hosp.& Unit No.","GP","Birth Weight","Working Diagnosis"];
var fieldName = "";
var field = "";
var decision = true;
var prompt = "";
var i = 0;
for (i = 0; i<fieldArray.length;i++)
{
field =eval("aform." + fieldArray[i]);
if(field.value =="")
{
fieldName = userNames[i];
decision = false;
break;
}
}

if (!decision){alert(fieldName + " is a required field. Please enter a value.");}
else { aform.submit(); prompt = "The form is being submitted.";alert(prompt);}

}

hendryk
07-26-2002, 06:28 PM
This is how the combo box is in the HTML form.

<td><SELECT NAME= "familyHistory">
<OPTION>No<OPTION>Yes<OPTION>Not Known</SELECT></td>


Hope this helps.

K

RadarBob
07-26-2002, 06:49 PM
I suspect you are talkingabout a <select> object. But your code is probably looking at only the first <option> in that <select> and the .value property is nothing (null/empty).

You need a function to iterate through the options to see if any are selected by checking the .selected property



function checkComboBox (thebox) {
var isSelected = new Boolean (false);

for (var i=0; i<thebox.length; i++) {
if (thebox.options[i].selected) {
isSelected = true;
}
}
return isSelected;
} / function checkComboBox


Now call it in your existing code. BUT you need to know if the field is a combo box. You don't want to call the above function for a text field!



....

for (i = 0; i<fieldArray.length;i++) {
field =eval("aform." + fieldArray[i]);

if (field.type == "select-one") {
decision = checkComboBox (field);
} else {
if(field.value =="") {
fieldName = userNames[i];
decision = false;
break;
}
}



P.S. I humbly disagree with break(ing) out in the middle of a loop as a general coding principle. First it really doesn't hurt to let it loop through the entire form. Second, if you do so you can be building an alert() dialog box that lists all the empty fields you find - good user interface feedback!!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum