This function has a set of radio inputs, for each radio there is a hidden text input. When a radio input is checked it shows its chained text input.
I've done it with a function constructor, and I could have done this with closures or with simpler invocation patterns. My idea is to have some robust function which I could extend.
I haven't tested browser compatibility, which is somehow important for my market (IE8 lovers).
<form>
<input type="radio" name="color" value="yellow" checked /><label>Yellow</label>
<input type="radio" name="color" value="brown" /><label>Brown</label>
<input type="radio" name="color" value="orange" /><label>Orange</label>
<input type="radio" name="color" value="purple" /><label>Purple</label>
<input type="text" id="value-yellow" class="radio-condition" placeholder="Which yellow?" />
<input type="text" id="value-brown" class="radio-condition" placeholder="Which brown?" />
<input type="text" id="value-orange" class="radio-condition" placeholder="Which Orange?" />
<input type="text" id="value-purple" class="radio-condition" placeholder="Which Purple?" />
</form>
// INSTRUCTIONS
// There is a hidden text input for each radio input.
// Checked radio will show its chained text input.
// They're chained by the radio value and the text id
// the radio value makes a string that is used as the id of the text
// Constructor Function
var JavaScript_form = function() {
this.radios = document.querySelectorAll('input[type="radio"]');
}
// Public method of instance
JavaScript_form.prototype.radio_hide_element = function() {
// inputs that will be hidden
var els_hidden = document.getElementsByClassName('radio-condition'),
els_hidden_length = els_hidden.length;
// loop each radio input
[].forEach.call(this.radios, function (el) {
var i = 0;
for (; i < els_hidden_length; i++) {
els_hidden[i].style.display = 'none';
}
els_hidden[0].style.display = 'block';
// click radio will toggle visibility of text input
el.addEventListener('click', function() {
var i = 0;
for (; i < els_hidden_length; i++) {
els_hidden[i].style.display = 'none';
els_hidden[i].value = '';
}
document.getElementById('value-' + this.value).style.display = 'block';
});
});
}
// Make instance
var JS_radios = new JavaScript_form();
JS_radios.radio_hide_element();