[英]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.