Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jul 2002
    Posts
    362
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Checkbox and Textbox validation

    Please advise as I would like to make sure a textbox is populated if a Checkbox is selected.

    My Checkbox has two selections with one already checked:
    Code:
    Account<input TYPE="Radio" name="account" value="Yes" CHECKED />Yes
    <input TYPE="Radio" name="account" value="No" />No
    <br>
    Names<TEXTAREA COLS="12" ROWS="3" NAME="names" WRAP="soft"></TEXTAREA>
    Now I need to make sure if it is checked "Yes" then a message will come up if the "Names" Box is blank.
    If the checkbox is checked with a "No" and the "Names" box is populated then I need an alert message saying the "No" checkbox should not be checked if the "Names" field is populated.


    My attempt:

    Code:
    var checked;
    
    if(document.myformnamehere.account.checked.value == "Yes")
    {
    	checked = true;
                 if(document.myformnamehere.names.value == "")
                 {
                           alert("names needs to be populated if account request is checked with yes");
                           return false;
                  }
     
    }
    else if(document.myformnamehere.account.checked.value == "No")
    {
    	checked = true;
                 if(document.myformnamehere.names.value != "")
                 {
                           alert("names can not  be populated if account request is checked with no");
                           return false;
                  }
     
    }

  • #2
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts
    <script language="JavaScript">
    function vd(){
    var strAlert='';
    //loop through the collection of radio buttons
    for (i=0;i<document.f1.account.length;i++){
    // if we find one that's checked
    if (document.f1.account[i].checked){
    //return its value
    strAccount=document.f1.account[i].value;
    }
    }

    switch(strAccount){
    case 'Yes':
    if (document.f1.names.value==''){
    strAlert='names needs to be populated';
    }
    break;
    case 'No':
    if (document.f1.names.value!=''){
    strAlert='names cannot be populated';
    }
    break;
    default:
    strAlert='You have broken our form'
    }
    if (strAlert!=''){
    alert(strAlert);
    }
    }
    </script>


    Any use?


  •  

    Posting Permissions

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