View Full Version : Dependent Required Fields

10-13-2008, 10:47 AM
If I have two text fields Box1 and Box2, and I want to make one of them required. So, if no value is filled in for Box1 then a value is required in Box2. And, if Box1 has been filled in, then Box2 cannot be filled in. I am using the following validation:

<script LANGUAGE="JavaScript">
function ValidateFld(){
if (document.frmDetails.UserName.value=='')
alert('Please enter a value for the Name field.');
if (document.frmDetails.email.value=='')
alert('Please enter a valid e-mail address.');

How can I acomplish this?
Thanks in advance

10-14-2008, 02:05 AM
Put each field next to a radio button. Initialize all fields as read-only. When a radio button is selected, enable its field and disable all others. You don't need to validate this on the server side because the values in the disabled fields won't matter.
<script type="text/javascript">
window.onload = function(){
var elements = document.forms.myform.elements;
var meta = {
previous: null
for(var i = 0; i < elements.length; i++){
if(elements[i].type == 'radio' && elements[i].name == 'which'){
elements[i].text = elements['which-' + elements[i].value];
elements[i].text.readOnly = true;
elements[i].onchange = toggle;
elements[i].meta = meta;
function toggle(){
this.meta.previous.readOnly = true;
this.text.readOnly = false;
this.meta.previous = this.text;
<form name="myform">
<input type="radio" name="which" value="1"><input type="text" name="which-1"><br>
<input type="radio" name="which" value="2"><input type="text" name="which-2">