This question is about an improvement of the code from this previous question (previous changed visibility, new applies a CSS class with a border).
It is a constructor function that attaches a click event to radio inputs using event delegation in order to add, remove CSS classes and enable the text input which contains a data-value equals to the radio value.
Short example
<label><input type="radio" name="color" value="yellow" checked />Yellow</label>
<input type="text" class="radio-condition visible" data-value="yellow" />
One important fact is that it must work for old browsers such as IE7-8. I know I'm using methods from EcmaScript 6 (is ES6 right?) such as classList which won't work. But I found this link from hacks.Mozilla.org where it shares a code for older browsers. So I guess I can use those ES6 methods safely, right?
jsFiddle here!
<script src="ie8_conditional_comments_with_script_from_hacks.Mozilla.js"></script>
<form>
<div id="radio-set" class="radio-set">
<label><input type="radio" name="color" value="yellow" checked />Yellow</label>
<label><input type="radio" name="color" value="brown" />Brown</label>
<label><input type="radio" name="color" value="orange" />Orange</label>
<label><input type="radio" name="color" value="purple" />Purple</label>
<input type="text" class="radio-condition visible" placeholder="Which yellow?" data-value="yellow" />
<input type="text" class="radio-condition" placeholder="Which brown?" data-value="brown" disabled />
<input type="text" class="radio-condition" placeholder="Which Orange?" data-value="orange" disabled />
<input type="text" class="radio-condition" placeholder="Which Purple?" data-value="purple" disabled />
</div>
</form>
<style>
.radio-condition {border: 1px solid red; display: block; margin-bottom: 2px}
.visible {border-color: green}
</style>
<script>
var JavaScript_form = function() {
// this.radio_set = document.getElementById('radio-set'),
this.radio_set = document.querySelector('radio-set'),
this.radios = document.querySelectorAll('input[type="radio"]');
}
//
JavaScript_form.prototype.radio_hide_element = function() {
// hide elements
var els_hidden = document.getElementsByClassName('radio-condition'),
els_hidden_length = els_hidden.length;
// Event handler that uses event delegation
document.getElementById('radio-set').addEventListener('click', function(e) {
// e.target was the clicked element
if (e.target && e.target.nodeName == 'INPUT' && e.target.getAttribute('type') == 'radio') {
console.log(e.target.value);
var inputs = document.querySelectorAll('.radio-condition'),
i = 0,
inputs_length = inputs.length;
for (; i < inputs_length; i++) {
inputs[i].classList.remove('visible');
inputs[i].disabled = true;
}
document.querySelector("[data-value='" + e.target.value + "']").className += ' visible';
document.querySelector("[data-value='" + e.target.value + "']").disabled = false;
}
});
}
var JS_radios = new JavaScript_form();
JS_radios.radio_hide_element();
</script>