How to make field required with JavaScript if checkbox is checked

March 13, 2015

Really simple solution that will allow you to make fields required below

Fields need to be required if checked:

<input type="checkbox" name="needRequired" id="needRequired" value="1" />
<input type="text" name="Name" id="Name" />
<script>
document.getElementById("needRequired").addEventListener('change', function(){
    document.getElementById("Name").required =  this.checked;
})
</script>
 

Fields don't need to be required if checked:

<input type="checkbox" name="needRequired" id="needRequired" value="1" />
<input type="text" name="Name" id="Name" required />
<script>
document.getElementById("needRequired").addEventListener('change', function(){
if(this.checked)
{
    document.getElementById("Name").required =  false;
}
else
{
    document.getElementById("Name").required =  true;
}
})
</script>