Search code examples
javascriptjqueryformscheckboxrequired

JavaScript if check-box is checked not working


I have a website form where I have fields that I want to be required (with JQuery Plugin) only when the check-box is checked.

So far I wrote JavaScript that works if the the check-box is not checked, or checked. But when a user checks the check-box and then unchecks it the code does not work (field is still mandatory when unchecked).

Also one other bug is for some reason this same code only works for updating only one items required boolean. For example if I have the same code but make it so two elements requirements are updated the script does not work at all.

Here is the relevant source code:

<script>
function swap(){
  if(document.getElementById('must').checked){     
    document.getElementById("element1").setAttribute("required", "true");
  }else{      
    document.getElementById("element1").setAttribute("required", "false");
  }
}
</script>


<form>
<input type="checkbox" onclick="swap();" id="must" name="must" value="1" style="width:10;">
<input id="element1" type="text" name="element1" placeholder="Enter Value" >
<input type="submit" id="submit" name="submit" value="Send" >
</form>     

Any assistance would be greatly appreciated.


Solution

  • Try this, in xhtml we specify required="required" and there no required="false", a better way is to remove attribute required on else

    <script type="text/javascript">
       function swap(){
      if(document.getElementById('must').checked){     
        document.getElementById("element1").setAttribute("required", "required");
      }else{      
        document.getElementById("element1").removeAttribute("required");
      }
    }
        </script>