【问题标题】:textbox must not be empty if checkbox is ticked如果选中复选框,则文本框不能为空
【发布时间】:2014-08-22 19:05:04
【问题描述】:

我有三个复选框。每个复选框旁边都有一个“姓名”和“年龄”文本框。 “Singles”复选框有一组这些文本框,而“Couples”复选框有两组。我正在寻找将在提交表单之前提供“警报”消息的代码,以说明如果选中了相应的复选框,则必须填写所有文本框。例如,如果只勾选了“Singles”复选框,则只有“Singles”文本框被选中。如果选中“Singles”和“Couples”,则“Singles”和“Couples”的文本框必须完整。我试过下面的代码:

请注意,还有一个检查以确保在开始时输入了“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;
    }

【问题讨论】:

    标签: validation if-statement checkbox textbox checked


    【解决方案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

    【讨论】:

    • 您好 Janani M,感谢您的回复。解决方案似乎合乎逻辑。
    • 谢谢.. 如果它有效,请接受答案/投票 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多