jquery自动获取和填充表单元素


//获取表单数据,返回json格式数据
/*
*因为项目涉及到大量的表单处理,字段一一对应会比较繁琐,所以写了个方法统一获取需要提交的表单元素
*公司用的easyui框架,所以对easyui表单元素有做相应处理,如不需要可以删除函数里面的if判断,只取else里面的内容即可
*思路:
*表单的字段id="数据库字段名 + _auto";
*radio和checkbox则是name="数据库字段名 + _auto";
*函数会遍历表单里面的所有最后有_auto的id或name,自动读取值到data,最后返回json格式数据
*调用方法:_getAutoObject('#form1');
*/

//null或undefined字段返回空字符串
function nullToSpace (v) {
  return !v && v != '0' ? '' : v;
}

//替代eval的函数
function evil (fn) {
  var Fn = Function; //一个变量指向Function,防止有些前端编译工具报错
  return new Fn('return ' + fn)();
}
function _getAutoObject(obj) {
  var data = {};
  obj = obj || 'body';
  // 找到元素,进行循环
  $(obj).find('*[id$=_auto],*[name$=_auto]').each(function () {
    var $t = $(this),
        $t_id = $t.attr('id'),
        $t_name = $t.attr('name'),
        $t_class = $t.attr('class'),
        $key;
    if ($t.attr('type') != 'radio' && $t.attr('type') != 'checkbox') {
      $key = $t_id;
    } else {
      $key = $t_name;
    }
    $key = $key.substring(0, $key.length - 5);
    //判断是否easyui表单组件
    if ($t_class && ($t_class.indexOf('combo-f') != '-1' || $t_class.indexOf('textbox-f') != '-1' || $t_class.indexOf('numberbox-f') != '-1' || $t_class.indexOf('validatebox-f') != '-1' || $t_class.indexOf('datebox-f') != '-1' || $t_class.indexOf('datetimebox-f') != '-1' || $t_class.indexOf('datetimespinner-f') != '-1' || $t_class.indexOf('numberspinner-f') != '-1')) {
      var c = $t_class.split('-f')[0].split(' '),
          isVals = '$("'+ obj +' #' + $key + '_auto").' + c + '("options").multiple',
          v = 'getValue';
      c = c[c.length - 1];
      if (c.indexOf('combo') != -1) {
        try {
          if (evil(isVals)) {
            v = 'getValues';
          }
        } catch (e) {

        }
      }
      var func = '$("'+ obj +' #' + $key + '_auto").' + c + '("' + v + '")';
      try {
        data[$key] = evil(func);
      } catch (e) {

      }
    } else {
      //普通表单元素
      if ($t.is('span') || $t.is('div') || $t.is('a') || $t.is('p')) {
        data[$key] = $t.text();
      } else if ($t.is('img')) {
        data[$key] = $t.attr('src');
      } else if ($t.is(':input')) {
        if ($t.attr('type') == 'checkbox') {
          data[$key] = 0;
          var c = '*[type="checkbox"][name="' + $key + '_auto"]',
              $val;
          if ($(c).length > 1) {
            $val = [];
            $(c).each(function (i) {
              if ($(c).eq(i).is(':checked')) {
                $val.push($(c).eq(i).val());
              }
            });
          } else {
            if ($t.is(':checked')) {
              if ($val == '' || $val == null || $val == 'on') {
                $val = 1;
              }
            } else {// 没有选中
              $val = 0
            }
          }
          data[$key] = $val;
        } else if ($t.attr('type') == 'radio') {
          data[$key] = '';
          var c = '*[type="radio"][name="' + $key + '_auto"]:checked';
          if ($(c).length > 0) {
            data[$key] = $(c).val();
          }
        } else {
          data[$key] = $t.val();
        }
      }
    }
  });
  return data;
}

//与上面相对应的,还有一个自动填充表单数据函数_showFormContent,思路差不多,只是略微复杂一点
/*html例如:
<style>
  .f-dn{
  display: none;
}
</style>
<form id="form">
  <input id="test_id_auto" type="hidden" value="1111111">
  <div>
    <div class="uname_auto"></div><!-- 数据库字段名 + _auto 结尾的class不会提交,用于显示默认字段内容 -->
    <div class="sex_auto"></div>
    <div class="textarea_auto"></div>
  </div>
  <table class="m-table">
    <tbody>
      <tr>
        <td align="right" valign="top">姓名: </td>
        <td valign="top">
          <input id="uname_auto" type="text">
          <span class="uname_ori f-dn"></span>
        </td>
        <td align="right" valign="top">性别: </td>
        <td valign="top">
          <select id="sex_auto">
            <option value="">-请选择-</option>
            <option value="1">男</option>
            <option value="2">女</option>
          </select>
          <span class="sex_ori f-dn"></span>
        </td>
      </tr>
      <tr>
        <td align="right" valign="top">自我介绍: </td>
        <td valign="top" colspan="3">
          <textarea id="textarea_auto"></textarea>
          <span class="textarea_ori f-dn"></span>
        </td>
      </tr>
    </tbody>
  </table>
</form>
*参数解析:
*data为json格式数据,函数会根据json匹配字段值到相应的元素
*operType有以下几种值:
  edit 编辑状态 数据填充到id="数据库字段名 + _auto"元素,表单仍可编辑
  detail 详情状态 数据填充到class="数据库字段名 + _ori"元素并显示,会自动移除相邻的表单元素,不能恢复编辑
  detail2 详情状态 数据填充到class="数据库字段名 + _ori"元素并显示,会自动隐藏相邻的表单元素,可以与edit状态互相切换
  clear 清除状态 将data数据里对应的字段值清空,select筛选时用到
*调用方法:
_showFormContent(data,'edit','#form1'); //如果页面只有一个表单需要填充,第三个参数可以不填,默认为body
_showFormContent(data,'detail','#form2');
_showFormContent(data,'detail2','#form3');
_showFormContent(data,'clear','#form4');
*/

function _showFormContent(data, operType, obj) {
  obj = obj || 'body';
  //初始化表单元素
  if (operType != 'clear') {
    var $t = $(obj).find('*[id$=_auto],*[name$=_auto]');
    $(obj).find(':input').removeAttr('disabled');
    $t.each(function (i) {
      var $t_class = $t.eq(i).attr('class'),
        $t_id = $t.eq(i).attr('id');
        $t_id = $t_id.substring(0, $t_id.length - 5);
      //判断是否easyui表单组件
      if ($t_class && ($t_class.indexOf('combo-f') != '-1' || $t_class.indexOf('textbox-f') != '-1' || $t_class.indexOf('numberbox-f') != '-1' || $t_class.indexOf('validatebox-f') != '-1' || $t_class.indexOf('datebox-f') != '-1' || $t_class.indexOf('datetimebox-f') != '-1' || $t_class.indexOf('datetimespinner-f') != '-1' || $t_class.indexOf('numberspinner-f') != '-1')) {
        var t_c = $t_class.split('-f')[0].split(' '),
          t_v = 'setValue';
        t_c = t_c[t_c.length - 1];
        try {
          evil('$("' + obj + '").find("#' + $t_id + '_auto").' + t_c + '("' + t_v + '","")');
        } catch (e) {

        }
        if (operType == 'detail' || operType == 'print' || operType == 'detail2') {
          $(obj).find('.' + $t_id + '_ori').show();
          $t.eq(i).next('span').hide();
        } else {
          $(obj).find('.' + $t_id + '_ori').hide();
          $t.eq(i).next('span').show();
        }
      } else {
        if ($t.eq(i).is(':input')) {
          $t.eq(i).val('');
        } else {
          $t.eq(i).html('');
        }
        $(obj).find('.' + $t_id + '_ori').html('');
        if (operType == 'detail' || operType == 'print' || operType == 'detail2') {
          $(obj).find(':input').attr('disabled', 'disabled');
          if ($t.eq(i).attr('type') != 'hidden') {
            $(obj).find('.' + $t_id + '_ori').show().siblings().hide();
          }
          if (operType != 'detail2') {
            $(obj).find('.' + $t_id + '_ori').siblings().remove();
          }
        } else {
          $(obj).find(':input').removeAttr('disabled');
            if ($t.eq(i).attr('type') != 'hidden') {
              $(obj).find('.' + $t_id + '_ori').hide().siblings().show();
            }
        }
      }
    });
    var showDetail = function (id, value) {
      if (operType == 'detail' || operType == 'print' || operType == 'detail2') {
        $(obj).find(id).html(value);
      }
    };
  }
  //填充数据
  if (nullToSpace(data) != '') {
    $.each(data, function (n, value) {
      if (operType == 'clear') {
        value = '';
      }
      var _id = '#' + n + '_auto', //表单需要提交的字段id
        _name = 'input[name="' + n + '_auto"]',
        _s_id = '.' + n + '_auto', //新增和编辑时需要默认显示的字段
        _ori_id = '.' + n + '_ori', //详情和打印时显示的字段
        $class = $(obj).find(_id).attr('class'),
        $type = $(obj).find(_id).attr('type');
      if ($(obj).find(_id).length > 0 || $(obj).find(_name).length > 0 || $(obj).find(_s_id).length > 0 || $(obj).find(_ori_id).length > 0) {
        if (typeof value == 'string') {
          if (value.indexOf('\r') != '-1' || value.indexOf('\n') != '-1' || value.indexOf('<w:br/>') != '-1') {
            if (operType == 'detail' || operType == 'print') {
              //详情换行转换
              value = value.replace(/(\r\n|\n|\r|<w:br\/>)/gm, '<br>');
            } else {
              if ($(obj).find(_id).is('textarea')) {
              //后台返回的数据如果有换行符时easyui表单控件会出现bug,需要转化换行符再执行函数
              value = value.replace(/(\r\n|\n|\r|<w:br\/>)/gm, '\r\n');
            }
          }
        }
      }
      value = nullToSpace(value);
      //判断是否easyui表单元素
      if ($(obj).find(_id).length > 0 && $class && ($class.indexOf('combo-f') != '-1' || $class.indexOf('textbox-f') != '-1' || $class.indexOf('numberbox-f') != '-1' || $class.indexOf('validatebox-f') != '-1' || $class.indexOf('datebox-f') != '-1' || $class.indexOf('datetimebox-f') != '-1' || $class.indexOf('datetimespinner-f') != '-1' || $class.indexOf('numberspinner-f') != '-1')) {
        var c = $class.split('-f')[0].split(' '),
          v = 'setValue';
        c = c[c.length - 1];
        var func = '';
        if (c.indexOf('combo') != -1 && String(value).length > 1) {
          try {
            if (typeof evil(value) == 'object') {
              v = 'setValues';
            }
          } catch (e) {

          }
        }
        func = '$("' + obj + '").find("#' + n + '_auto" ).' + c + '("' + v + '","' + value + '")';
        evil(func);
        if ($class.indexOf('combo-f') != '-1') {
          var $text = $(obj).find(_id).combo('getText');
          $(obj).find(_s_id).html($text);
          showDetail(_ori_id, $text);
        } else {
          $(obj).find(_s_id).html(value);
          showDetail(_ori_id, value);
        }
      } else {
        $(obj).find(_s_id).html(value);
          //普通表单元素
          if ($(obj).find(_name).length > 0) {
            $(obj).find(_name).removeAttr('checked');//初始清空样式
            if ($(obj).find(_name).attr('type') == 'checkbox') {
              if (typeof value != 'object') {
                if (value == '1') {
                  $(obj).find(_name).attr("checked", true).prop('checked', true);
                }
              } else {
                var v = '';
                $.each(value, function (a, k) {
                  $(obj).find(_name + '[value="' + k + '"]').attr("checked", true).prop('checked', true);
                  if (a == 0) {
                    v += k;
                  } else {
                    v += ',' + k;
                  }
                });
                $(obj).find(_s_id).html(v);
                showDetail(_ori_id, v);
              }
            } else if ($(obj).find(_name).attr('type') == 'radio') {
              if (value != '' || value == '0') {
                $(obj).find(_name + '[value="' + value + '"]').attr("checked", true).prop('checked', true);
                $(obj).find(_s_id).html(value);
                showDetail(_ori_id, value);
              }
            }
          } else {
            if ($(obj).find(_id).is(':input')) {
              $(obj).find(_id).val(value);
            } else if ($(obj).find(_id).is('img') && value != '') {
              $(obj).find(_id).attr('src', value).show().siblings().hide();
            } else {
              $(obj).find(_id).html(value);
            }
            showDetail(_ori_id, value);
          }
        }
      }
    });
  }
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM