textbox must not be empty if checkbox is ticked

半世苍凉 提交于 2019-12-13 01:29:55

问题


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:


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



来源:https://stackoverflow.com/questions/25425296/textbox-must-not-be-empty-if-checkbox-is-ticked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!