Thread: Validate

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    21
    Rep Power
    0

    Validate


    Hi,

    i have the form with mutiple fields. If i select one check box Other, the text box must be required. The code i have below didn't work, can you pls tell me why?


    if ((other.checked = 1) &&
    (document.getElementById ("other_text").value.length == 0))
    {
    alert("You must enter the other information.");
    return false;
    }


    return true;

    }
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,136
    Rep Power
    120
    I removed a few of the extra unneeded parentheses, added a ELSE condition, added a couple variables and added a logical "OR" operator, so that both of your form fields must be validated correctly; in order, to submit your form.
    Code:
    <script>
    
    function doubleCheck()
    {
    var other = document.getElementById ("other");
    var txtInput = document.getElementById ("other_text").value.length;
     if (other.checked == false || txtInput == 0)
      {
       alert("You must enter the other information.");
      }
     else {
      document.getElementById("myForm").submit();
     }
    }
    
    function readyForm()
    {
    document.getElementById("myForm").onsubmit = function(){
      doubleCheck();
      return false;
     }
    }
    
    window.onload = function() {
     readyForm();
    }
    
    </script>
    
    <form id="myForm">
    <input id="other" type="checkbox"/>
    <input id="other_text" type="text"/>
    <input type="submit"/>
    </form>

IMN logo majestic logo threadwatch logo seochat tools logo