繁体   English   中英

单击复选框后,然后需要表单字段吗?

[英]Once Checkbox is clicked on, form fields then become required?

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

<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代码使其达到我需要的功能时获得一些帮助。 任何帮助将非常感激!

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

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

我试图让您对此尽可能清楚。 只要阅读评论,一切都应该很好。

<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>

如果您有任何问题,请通知我。 希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM