javascript - 使用编辑模式创建表单

标签 javascript forms

您知道如何创建具有编辑模式的表单吗?有关详细信息:假设我有一个包含 5 或 6 个字段的表单,其中包含按钮 'Save' 和 'Cancel' 。如果我保存表单,它将显示没有文本字段的纯表单,并且会出现一个名为“编辑”的按钮。当我点击“编辑”时,表格将是可编辑的。可能吗?

最佳答案

完整示例,可以处理任意数量的输入字段。(无选择、文本区域..)

代码是基于现代浏览器用纯javascript和css3编写的。

在 Chrome 上测试。

用css3隐藏和显示按钮,

保存默认值以在取消时应用它们,

响应输入按钮。

如果有任何问题..就问

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Modern Form</title>
<style>
label{display:block;}
form input{border:none;outline:none;box-sizing:border-box;}
form.invert input{border:1px solid rgba(0,0,0,0.2);outline:none;}

form>button:nth-of-type(1){
 color:green;display:none;
}
form>button:nth-of-type(2){
 color:red;display:none;
}
form>button:nth-of-type(3){
 color:yellow;display:inline-block;
}
form.invert>button:nth-of-type(1){
 display:inline-block;
}
form.invert>button:nth-of-type(2){
 display:inline-block;
}
form.invert>button:nth-of-type(3){
 display:none;
}
</style>
<script>
(function(W){
 var D,form,bts,ipt;
 function init(){
  D=W.document,previous=[];
  form=D.getElementsByTagName('form')[0];
  bts=form.getElementsByTagName('button');
  ipt=form.getElementsByTagName('input');
  form.addEventListener('submit',save,false);
  bts[1].addEventListener('click',cancel,false);
  bts[2].addEventListener('click',edit,false);
 }
 function save(e){
  e.preventDefault();
  form.classList.remove('invert');
  var l=ipt.length;
  while(l--){
   ipt[l].readOnly=true;
  };
  previous=[];
  //send your info here 
 }
 function edit(e){
  e.preventDefault();
  form.classList.add('invert');
  var l=ipt.length;
  while(l--){
   previous[l]=ipt[l].value;
   ipt[l].readOnly=false;
  }
 }
 function cancel(e){
  form.classList.remove('invert');
  e.preventDefault();
  var l=ipt.length;
  while(l--){
   ipt[l].value=previous[l];
   ipt[l].readOnly=true;
  }
 }
 W.addEventListener('load',init,false);
})(window)
</script>
</head>
<body>
<form>
<label>A:<input readonly></label>
<label>B:<input readonly></label>
<label>C:<input readonly></label>
<button>Save</button><button>Cancel</button><button>Edit</button>
</form>
</body>
</html>

ps: 处理函数可以合并成一个更大的函数...但我认为这样更容易理解

关于javascript - 使用编辑模式创建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18301368/

相关文章:

javascript - JQuery Post 错误 react

javascript - 如何重新初始化已从 DOM 中删除的按钮?

javascript - 使用预填充的表单,仅提交更改的字段

javascript - 表单不传递 iframe 输入

javascript - 清除一页上的多个表单

asp.net - 我如何使用 jQuery 插入一个 <DIV> 包裹在可变数量的子元素周围?

javascript - 将 react 组件(或元素?)放入对象中。

javascript - 防止 Ajax.Complete 内部出现循环

javascript - 拉取第一个输入实例并通过 JS 添加 id

javascript - 当 'ESC' 键触发事件时,未在 keydown 事件上提交表单