每次用户选中单选按钮代码就会检测用户师傅选择了other选项。
- 如果选择的other选项将显示一个文本输入框。
- 如果选择了前两个选项。将隐藏文本框并将文本框里的值清空。
HTML
<form name="" action="" method="post">
<input type="radio" name="heard" value="search" id="search" />
<label for="search">Search engine</label><br>
<input type="radio" name="heard" value="print" id="print" />
<label for="print">Newspaper or magazine</label><br>
<input type="radio" name="heard" value="other" id="other" />
<label for="other">Other</label><br>
<input type="text" name="other-input" id="other-text" />
<input id="submit" type="submit" value="submit" />
</form>
<script src="js/utilities.js"></script>
<script src="js/input-type.js"></script>
utilities.js
<span style="font-weight: normal;"><span style="font-size:12px;">// Helper function to add an event listener
function addEvent (el, event, callback) {
if ('addEventListener' in el) { // If addEventListener works
el.addEventListener(event, callback, false); // Use it
} else { // Otherwise
el['e' + event + callback] = callback; // CreateIE fallback
el[event + callback] = function () {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
// Helper function to remove an event listener
function removeEvent(el, event, callback) {
if ('removeEventListener' in el) { // If removeEventListener works
el.removeEventListener(event, callback, false); // Use it
} else { // Otherwise
el.detachEvent('on' + event, el[event + callback]); // Create IE fallback
el[event + callback] = null;
el['e' + event + callback] = null;
}
}</span></span>
input-type.js
(function() {
var form, options, other, otherText, hide; // Declare variables
form = document.getElementById('how-heard'); // Get the form
options = form.elements.heard; // Get the radio buttons
other = document.getElementById('other'); // Other radio button
otherText = document.getElementById('other-text'); // Other text input
otherText.className = 'hide'; // Hide other text input
for (var i = [0]; i < options.length; i++) { // Loop through radios
addEvent(options[i], 'click', radioChanged); // Add event listener
}
function radioChanged() {
hide = other.checked ? '' : 'hide'; // Is other checked?
otherText.className = hide; // Text input visibility
if (hide) { // If text input hidden
otherText.value = ''; // Empty its contents
}
}
}());