绑定单/复选框和文本框

绑定单/复选框和文本框

/*
 * @param {string | object} box checkbox/radio的对象或者id
 * @param {string | object} input input的对象或者id
 */
 function bindBoxAndInput(box, input) {
     if (typeof box === 'string') {
         box = document.getElementById(box);
     }
     if (typeof input === 'string') {
         input = document.getElementById(input);
     }
     if (!box || !input) return;

     box.addEventListener('click', function() {
         if (box.checked) {
             input.focus();
         } else {
             input.value = '';
         }
     })
     input.addEventListener('input', function() {
         if (input.value.trim()) {
             box.checked = true;
         } else {
             box.checked = false;
         }
     })
 }
原文地址:https://www.cnblogs.com/wangdapeng/p/6814476.html