textbox must not be empty if checkbox is ticked

2019-08-03 17:38发布

I have three checkboxes. Each checkbox has a 'name' and 'age' text box next to them. 'Singles' checkbox box has one set of these textboxes while 'Couples' checkbox has two sets. I'm looking for code which will provide an 'alert' message prior to submitting a form to say all textboxes must be filled in if corresponding checkbox is ticked. For instance, if only 'Singles' checkbox is ticked, only 'Singles' Textboxes to be checked. If 'Singles' and 'Couples' Checked, Textboxes for 'Singles' and 'Couples' must be complete. I've tried the below code:

Please note, there is also a check to make sure a 'yournameis' is entered at the start and that indeed a checkbox is ticked. Thanks.

  function validate_checkboxform( form )
    {
        //Custom Validation Steps
        if( ltrim(rtrim(form.elements['yournameis'].value,' '),' ')=="" ) { alert("Please enter text. "); form.elements['yournameis'].focus(); return false; }
        //Custom Validation for element
        var fo = document.checkboxform;
        var checkboxform=document.getElementById("checkboxform"); 
    if (!fo.singles1.checked && !fo.couples1.checked && !fo.families1.checked) {
          alert("You must select at least one option.");
          return false;
    }
       if (this.singles1.checked && this.singlesname1.value=="") {
          alert("Please enter something in input 1");
          this.singlesname1.focus();
          return false;
        }
        if (this.couples1.checked && this.couplesname1.value=="") {
          alert("Please enter something in input 2");
          this.couplesname1.focus();
          return false;
      }
        return true;
    }

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-03 18:05
function validate_checkboxform( form )
{
  if($('#isCheckBox').is(':checked') && $("#textBox").val().length <0)
     alert("value of textBox needed..");
}
<input type="checkbox" id="isCheckBox"/>
<input type="text" id="textBox"/>

Repeat the same for 3 checkboxes & inputs fiddle 'd here

查看更多
登录 后发表回答