那天写了一篇文章用于在不提交表单的情况下,重置form的reset后的值,但是那个方法有两个缺点,而这两个缺点是致命性的,1,textarea控件没办法解决,2, ie不支持,正因为第2个原因,所以不能使用这种方法。
但是,这种方法也提供了解决这个问题的思路:我们要在表单保存的时候,记录下当前控件的值,然后在reset的时候恢复这个值。既然浏览器做不了,只能在代码中做了。其实就是在保存的时候,用一个属性值来记录下控件的值,然后我们自己实现form的reset的方法,这个方法用来读取这个属性的值,重新赋值。
赋值代码:
function changeCheckValAttr(helement) {
var checks = helement.checked; if (checks) { helement.setAttribute("origin-data", "checked"); } else { helement.setAttribute("origin-data", "unchecked"); } } //用来记录类似radio,checkbox控件的值 function changeCommonTextValAttr(helement) { helement.setAttribute("origin-data", helement.value); } //用来记录普通空间的值 都以origin-data属性来记录
获取值代码:
// select控件
function getSelectValAttr(helement) {
var j = 0, options = helement.options, t, selVal;
selVal = helement.getAttribute("origin-data");
if (selVal != null) {
for ( ; j < options.length; j++) {
var odata = options[j]
if (selVal == options[j].value) {
options[j].setAttribute("selected", "selected");
} else {
options[j].removeAttribute("selected");
}
}
}
}
//check控件
function getCheckValAttr(helement) {
var checks = helement.getAttribute("origin-data");
if (checks != null) {
if (checks == "checked") {
helement.setAttribute("checked", "checked");
} else {
helement.removeAttribute("checked");
}
}
}
// text
function getCommonTextValAttr(helement) {
var ovalue = helement.getAttribute("origin-data");
if (ovalue != null) {
helement.setAttribute("value", ovalue);
}
}
// textarea
function getTextAreaValAttr(helement) {
var ovalue = helement.getAttribute("origin-data");
if (ovalue != null) {
helement.innerHTML = ovalue;
}
}
主逻辑代码:
function setOrginDataAttr(helement) { var tagName = helement.tagName, tagType = helement.type; if (tagName.toUpperCase() == "INPUT" && tagType == "text") { changeCommonTextValAttr(helement); } else if (tagName.toUpperCase() == "TEXTAREA") { changeCommonTextValAttr(helement); } else if (tagName.toUpperCase() == "SELECT") { changeCommonTextValAttr(helement) } else if (tagName.toUpperCase() == "INPUT" && tagType == "checkbox") { changeCheckValAttr(helement); } else if (tagName.toUpperCase() == "INPUT" && tagType == "radio") { changeCheckValAttr(helement); } } function getOrginDataAttr(helement) { var tagName = helement.tagName, tagType = helement.type; if (tagName.toUpperCase() == "INPUT" && tagType == "text") { getCommonTextValAttr(helement); } else if (tagName.toUpperCase() == "TEXTAREA") { getTextAreaValAttr(helement); } else if (tagName.toUpperCase() == "SELECT") { getSelectValAttr(helement) } else if (tagName.toUpperCase() == "INPUT" && tagType == "checkbox") { getCheckValAttr(helement); } else if (tagName.toUpperCase() == "INPUT" && tagType == "radio") { getCheckValAttr(helement); } } function setFormOriginDataAttrs(aform) { $.map(aform[0].elements, setOrginDataAttr); } function resetFormToOriginData(aform) { $.map(aform[0].elements, getOrginDataAttr); }
调用resetFormToOriginData方法之前记得调用form原生的reset方法,
以防止当前控件没有origin-data后,重置form。