Results 1 to 2 of 2

Thread: Dependent Required Fields

  1. #1
    Join Date
    Aug 2005
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Dependent Required Fields

    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.');
    return;
    }
    if (document.frmDetails.email.value=='')
    {
    alert('Please enter a valid e-mail address.');
    return;
    }
    document.frmDetails.submit();
    }
    </script>


    How can I acomplish this?
    Thanks in advance

  2. #2
    Join Date
    Jul 2006
    Posts
    497
    Thanks
    8
    Thanked 70 Times in 70 Posts

    Default

    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.
    Code:
    <html>
        <head>
            <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(){
                        if(this.meta.previous){
                            this.meta.previous.readOnly = true;
                        }
                        this.text.readOnly = false;
                        this.meta.previous = this.text;
                    }
                };
            </script>
        </head>
        <body>
            <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">
            </form>
        </body>
    </html>
    -- Chris
    informal JavaScript student of Douglas Crockford
    I like wikis - a lot.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •