【问题标题】:Once Checkbox is clicked on, form fields then become required?单击复选框后,表单字段将变为必需吗?
【发布时间】:2014-12-28 03:14:27
【问题描述】:

我正在使用一个复选框,它会在单击该复选框时显示/隐藏字段。我想让我的字段仅在我单击复选框并且显示字段时才需要输入信息。当字段被隐藏并且未单击复选框时,则不需要这些字段输入信息。我该如何做到这一点。这是我正在使用的代码;

<script type="text/javascript" language="JavaScript">
function HidePart(d) { 
document.getElementById(d).style.display = "none";
}
function ShowPart(d) { 
document.getElementById(d).style.display = "block"; 
}
function CheckboxChecked(b,d)
{
if(b) {
ShowPart(d); 
}
else  { 
HidePart(d); 
}
}
</script>


  <input type="checkbox" name="Loan2" value="yes" onclick="CheckboxChecked(this.checked,'checkboxdiv2')"> Add New Loan


<div id="checkboxdiv2" style="display:none">
Form Fields for input information
</div> 

如果有帮助,这是我的网站:https://www.slfpusa.org/testing-page/。当我单击“添加新贷款”时,它会生成更多字段,我只想在它们显示时才需要这些字段。我希望我的问题很清楚,并且我希望在调整此 javascript 代码以按照我需要的方式运行时获得一些帮助。任何帮助将不胜感激!

【问题讨论】:

  • 你的表单在点击时没有提交 - 你的导入脚本有问题 -

标签: javascript html checkbox custom-fields required


【解决方案1】:

将您的表单验证代码放入额外的if 语句中。试试这样的:

if (document.loan2.checked) {
  // validate the input
} else {
  return false;
}

【讨论】:

    【解决方案2】:

    我尽量让你明白这一点。只需阅读 cmets,一切都会好起来的。

    <html>
    <head>
      <!--Add this JQuery library to make this a whole lot easier for you-->
      <!--This library provides a more effecient way of writing javascript-->
       <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    </head>
    
    <body>
      <form>
      <input id ="checkboxId" type ="checkbox">Add new Loan</input><br>
    
        <label style="display:none">Enter value:</label>
        <input id="textboxId" style="display:none" type ="text"/>
      <button style="display:none" type ="submit">Click Me</button>
    </form>
    
    <script>
    
    //In between your script tags add the following JQuery code
    
    //This will check if the check box is clicked
    $('#checkboxId').click(function () {
    
      //if checkbox is clicked then make the textbox required
      if ($('#checkboxId').prop('checked'))
      {
        $("#textboxId").prop('required',true);
            $("#textboxId").slideDown();
            $("label").slideDown();
            $("button").slideDown();
      } else {
        //else do not make the textbox required
        $("#textboxId").prop('required',false);
          $("#textboxId").slideUp();
          $("label").slideUp();
          $("button").slideUp();
      }
    
    });
    </script>
    </body>
    </html>
    

    如果您有任何问题,请告诉我。希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-07
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      相关资源
      最近更新 更多