Rob Rob - 5 months ago 10
Javascript Question

Text inputs required only when their div isn't hidden?

I'm looking for some advice on a way to have a few inputs only be set as "required" if the div they're in isn't hidden.

Here is the javascript I use to show the hidden div:

function ShowHide(){
if(document.getElementById('addressY').checked){
document.getElementById("addressT").style.display = "block";
} else {
document.getElementById("addressT").style.display = "none";
}
}


And an example of the hidden DIV input forms:

<label class="col-md-4 control-label" for="radios"><b>Did you find an address where the company accepts payments?</b></label>
<div class="col-md-4">
<div class="radio"><label for="radios-1"><input id="addressY" name="spelling" onchange="ShowHide()" required="" type="radio" value="yes" /> Yes </label></div>

<div class="radio"><input id="addressN" name="spelling" onchange="ShowHide()" required="" type="radio" value="no" /> No</div>
</div>
</div>

<div id="addressT" style="display: none;">&nbsp;
<div class="form-group"><b><label class="col-md-4 control-label" for="Full Address">Please fill in the full address that you found.</label> </b>

<div class="col-md-4"><label for="radios-0">Make Check Payable To (Optional): <input class="form-control input-md" id="address1" name="address1" placeholder="" style="width: 100%;" type="text" /></label>
</div>


You can see an example of the full form in action here.

If you can think of a better way to do this, I would love to hear this. I'm a relative beginner to javascript and jquery.

Answer

Here if you hide element and disable the radio buttons then your problem is solved so,

function ShowHide(){
if(document.getElementById('addressY').checked){
    document.getElementById("addressT").style.display = "block";
    for (var i=0, iLen=radios.length; i<iLen; i++) {
           radios[i].disabled = false;
        }
} else {
    document.getElementById("addressT").style.display = "none";
        var radios = document.querySelectorAll("[name='addresstype']")

        for (var i=0, iLen=radios.length; i<iLen; i++) {
           radios[i].disabled = true;
        } 
    }
}