I want to show/hide form inputs if particular radio buttons are selected.
I moved the hide functionality into a function to reduce repetition of code, but each time a radio button is checked I get the error: elems[i] is undefined
Can someone advise why this is occuring?
<form>
<fieldset id="contact-methods">
<legend>Preferred contact method</legend>
<div>
<input type="radio" id="phoneyes" name="preferred-method">
<label for="phoneyes" class="radio-label">Phone</label>
<input id="yourphone" name="Yourphone" value="enter phone number" class="hint dependant">
</div>
<div>
<input type="radio" id="emailyes" name="preferred-method">
<label for="emailyes" class="radio-label">Email</label>
<input id="youremail" name="Email" value="enter email address" class="hint dependant">
</div>
<div>
<input type="radio" id="postyes" name="preferred-method" class="textarea-label">
<label for="postyes" class="textarea-label radio-label">Post</label>
<textarea id="youraddress" rows="2" cols="40" name="Address" class="hint dependant">enter postal address</textarea>
</div>
</fieldset>
</form>
// Initially disable and hide depandant inputs.
$('.dependant').each(function(){
$(this).attr('disabled', true).hide();
});
function disableElem(elems){
var i = 0;
for ( i=0; i <= elems.length; i++){
elems[i].attr('disabled', true).hide();
}
}
// Show/hide contact methods when checked
$('#contact-methods').click(function(e){
var method = $(e.target).attr('id');
if(method === 'phoneyes'){
$('#yourphone').removeAttr('disabled').show();
hideOptions = [$('#youremail'), $('#youraddress')];
disableElem(hideOptions)
}
if(method === 'emailyes'){
$('#youremail').removeAttr('disabled').show();
hideOptions = [$('#yourphone'), $('#youraddress')];
disableElem(hideOptions)
}
if(method === 'postyes'){
$('#youraddress').removeAttr('disabled').show();
hideOptions = [$('#youremail'), $('#yourphone')];
disableElem(hideOptions)
}
});// closing show/hide contact methods