Javascript – Creating form with edit mode

formsjavascript

Do you know how to create a form with edit mode? For details: Suppose I've a form with 5 or 6 fields which has button 'Save' and 'Cancel' . If I save the form, it'll show the plain form without text fields and a button named 'Edit' will appear. And When I'll click on 'edit', the form will be editable. Is it possible?

Best Answer

Full example, can handle as many input fileds as you want.(no select,textarea..)

The code is written based on modern browsers in pure javascript and css3.

Tested on Chrome.

hides and shows the buttons with css3,

saves the default values to apply them on cancel,

responds on the enter button.

If any questions .. just ask

<!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: the handler function could be merged into one bigger function... but i think this way it's easier to understand