如果勾选了复选框,则文本框不能为空

时间:2014-08-21 11:33:39

标签: validation if-statement checkbox textbox checked

我有三个复选框。每个复选框旁边都有一个“名称”和“年龄”文本框。 “单曲”复选框有一组这些文本框,而“情侣”复选框有两组。我正在寻找能够在提交表单之前提供“警报”消息的代码,以便在勾选相应的复选框时必须填写所有文本框。例如,如果仅选中“单曲”复选框,则仅选中“单曲”文本框。如果'单身'和'夫妻'被选中,'单身'和'情侣'的文本框必须完整。我尝试过以下代码:

请注意,还有一项检查,以确保在开始时输入'yournameis',确实勾选了一个复选框。谢谢。

  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 个答案:

答案 0 :(得分: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"/>

对3个复选框重复相同的操作。输入fiddle 'd here