PDA

View Full Version : form validation using a select field



jc_gmk
05-20-2008, 09:50 AM
1) Script Title:
Required field(s) validation
2) Script URL (on DD):
http://www.dynamicdrive.com/dynamicindex16/requiredcheck.htm
3) Describe problem:

Is this script supposed to work on a 'select' field?

Works great for everything else except select.
e.g.


<select name="selectsomething">
<option value="" selected="selected">Please Select...</option>
<option value="opt1">OPT 1</option>
<option value="opt2">OPT 2</option>
</select>

If no option is selected the form still validates.

rangana
05-20-2008, 10:00 AM
You need to set it in your JS:


<script language="JavaScript">
<!--

/***********************************************
* Required field(s) validation v1.10- By NavSurf
* Visit Nav Surf at http://navsurf.com
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function formCheck(formobj){
// Enter name of mandatory fields
var fieldRequired = Array("FirstName", "LastName","selectsomething");
// Enter field description to appear in the dialog box
var fieldDescription = Array("First Name", "Last Name");
// dialog message
var alertMsg = "Please complete the following fields:\n";

var l_Msg = alertMsg.length;

for (var i = 0; i < fieldRequired.length; i++){
var obj = formobj.elements[fieldRequired[i]];
if (obj){
switch(obj.type){
case "select-one":
if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "select-multiple":
if (obj.selectedIndex == -1){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "text":
case "textarea":
if (obj.value == "" || obj.value == null){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
default:
}
if (obj.type == undefined){
var blnchecked = false;
for (var j = 0; j < obj.length; j++){
if (obj[j].checked){
blnchecked = true;
}
}
if (!blnchecked){
alertMsg += " - " + fieldDescription[i] + "\n";
}
}
}
}
var opt=document.formcheck.selectsomething;
if(opt.value=='')
{
alertMsg +=' - ' + 'selectsomething' +'\n';
} if (alertMsg.length == l_Msg){
return true;
}else{
alert(alertMsg);
return false;
}
}
// -->
</script>


See highlighted ;)

jc_gmk
05-20-2008, 10:44 AM
It doesn't seem to work.

With that extra code there none of the fields appear to be checked.

rangana
05-20-2008, 11:18 AM
What you mean by not working?..Have you changed the higlighted to what your form name is:


var opt=document.formcheck.selectsomething;


...also, selectsomething is your select element's name, which I'm basing from your previous post.
If nothing works, could you up your markups (HTML) as well :)

jc_gmk
05-20-2008, 03:07 PM
ah yes, my mistake.

Thanks for your help