通过复选框javascript切换必填字段

时间:2018-11-07 11:16:18

标签: javascript html checkbox toggle

我已经搜索了一段时间,这是我想出的,但是它不起作用:

<form action="Subscription.php" method="post">
     <label>field1<a style="color:red">*</a></label>
     <input type="text" id="field1" name="field1" pattern="^[A-Za-z -]+$" required>              

     <input type="checkbox" name="checkbox1" onclick="showMe('more'); togglerequirement();">Do you want more?

     <div id="more" style="display:none">
          <label>field2<a style="color:red">*</a></label>
          <input type="text" id="field2" name="field2" pattern="^[A-Za-z -]+$">
     </div>          
     <input type="submit" value="Invia richiesta di registrazione" class="btn" </form>

<script type="text/javascript">
function showMe (box) {
    var chboxs = document.getElementsByName("more");
    var vis = "none";
        if(chboxs[0].checked) {
            vis = "block";
        }
    document.getElementById(box).style.display = vis;
}

function togglerequirement(){
    var checkbox = document.getElementsByName("more");
    var field2= document.getElementsByid("field2");

    if(checkbox[0].checked){
        field2.setAttribute("required", "");
    }else{
        field2.removeAttribute("required");
    }
}
</script>

在您说任何我已经尝试过的fiedl2.required之前;而且无论哪种方式都行不通。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您正试图找到一个名为“更多”的复选框,但其名称为“ =“ checkbox1”:

<input type="checkbox" name="checkbox1" onclick="showMe('more'); togglerequirement();">

它可以正常工作,但是它将第二个字段在显示时更改为必填字段,而在隐藏时将其更改为不需要字段。因此您看不到任何效果。

Not required here

Required here

如果我完全了解您,请尝试以下操作:

<form action="Subscription.php" method="post">
     <label>field1<a style="color:red">*</a></label>
     <input type="text" id="field1" name="field1" pattern="^[A-Za-z -]+$" required>              

     <input type="checkbox" name="more" onclick="showMe('more'); togglerequirement();">Do you want more?

     <div id="more" style="display:none">
          <label>field2<a style="color:red">*</a></label>
          <input type="text" id="field2" name="field2" pattern="^[A-Za-z -]+$">
     </div>          
     <input type="submit" value="Invia richiesta di registrazione" class="btn" </form>

<script type="text/javascript">
function showMe (box) {
    var chboxs = document.getElementsByName("more");
    var vis = "none";
        if(chboxs[0].checked) {
            vis = "block";
        }
    document.getElementById(box).style.display = vis;
}

function togglerequirement(){
    var checkbox = document.getElementsByName("more");
    var field2 = document.getElementById("field2");

    if(checkbox[0].checked){
        field2.setAttribute("required", "");
    }else{
        field2.removeAttribute("required");
    }
}
</script>