mercredi 7 novembre 2018

toggle required field via checkbox javascript

I've searched this issue for a while now and this is what I came up with, but it doesnt work:

<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.getElementById("more");
    var field2= document.getElementsByid("field2");

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

Before you say anything I've already tried with fiedl2.required; and it doesnt work either way.

What can I do?




Aucun commentaire:

Enregistrer un commentaire