绑定单/复选框和文本框

绑定单/复选框和文本框

/*
 * @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;
         }
     })
 }
posted @ 2017-05-05 18:35  peng2015  阅读(791)  评论(0编辑  收藏  举报