2014-12-28 84 views
0

我正在使用複選框,並在單擊複選框時顯示/隱藏字段。我想讓我的字段只有在點擊複選框並顯示字段時才需要輸入信息。當字段被隱藏,並且複選框沒有被點擊時,那些字段不需要輸入信息。我如何做到這一點。這是我正在使用的代碼;一旦複選框被點擊,表單字段,然後成爲必需的?

<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代碼以便以我需要的方式運行。任何幫助將非常感激!

+0

你的表單在點擊時不會提交 - 導入腳本有問題--應該是部分 – user1428716

回答

0

將表單驗證代碼放入額外的if聲明中。嘗試這樣的事情:

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

我應該把那個額外的if else語句放在哪裏?我如何把它放在我現在的代碼中?

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

我試着讓這個儘可能清晰。只要閱讀評論,一切都應該很好。

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

如果您有任何問題,讓我知道。希望這可以幫助

相關問題