jquery常用表单操作
Posted York
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery常用表单操作相关的知识,希望对你有一定的参考价值。
//js将表单序列化成对象 $.fn.serializeObject = function () { var $els = $(this).find("[name]"); var formData = {}; var len = $els.length; for (var i = 0; i < len; i++) { var $item = $($els[i]); var name = $item.attr("name"); var type = $item.attr("type"); if (type == "checkbox") { formData[name] = $item.is(‘:checked‘); } else { formData[name] = $item.val(); } } return formData; }; /*根据name给子元素的Text赋值*/ $.fn.SetChildsText = function (model) { var el = this.find("[name]"); var elCount = el.length; if (elCount > 0) { for (var i = 0; i < elCount; i++) { $itemEl = $(el[i]); var name = $itemEl.attr("name"); var formatterFun = $itemEl.attr("data-formatter"); var value = model[name]; if (value != null) { if (typeof (window[formatterFun]) == "function") { value = window[formatterFun](value); } $itemEl.text(value); } else { $itemEl.text(""); } } } }; /*获取查询参数*/ function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } /** * 绑定下拉框 * @param {any} selId:下拉框Id * @param {any} url * @param {any} idField * @param {any} valueField * @param {any} initValue:初始值 */ function BindSelect(selId, url, idField, valueField, initValue) { $.get(url, function (data) { var len = data.length; var selItems = []; for (var i = 0; i < len; i++) { selItems.push(‘<option value="‘ + data[i][idField] + ‘">‘ + data[i][valueField] + ‘</option>‘); } $("#" + selId).append(selItems); if (initValue) { $("#" + selId).val(initValue); } }); } /*表单赋值*/ function FormLoad(formId, data) { var $form = $("#" + formId); $.each(data, function (name, ival) { var $oinput = $form.find("input[name=" + name + "]"); if ($oinput.attr("type") == "radio" || $oinput.attr("type") == "checkbox") { $oinput.each(function () { if (Object.prototype.toString.apply(ival) == ‘[object Array]‘) {// 是复选框,并且是数组 for (var i = 0; i < ival.length; i++) { if ($(this).val() == ival[i]) $(this).attr("checked", "checked"); } } else { if ($(this).val() == ival) $(this).attr("checked", "checked"); } }); } else if ($oinput.attr("type") == "textarea") {// 多行文本框 $form.find("[name=" + name + "]").html(ival); } else { $form.find("[name=" + name + "]").val(ival); } }); }
以上是关于jquery常用表单操作的主要内容,如果未能解决你的问题,请参考以下文章