inline edit with Ajax+JavaScript
by José Luis Rojo
July 09, 2019
HTML
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
<p id="ejemplo" class="edit">Clic para editar el texto y proceder a guardarlo en la base de datos.</p>
</div>
CSS
body{
margin: 10px 0px;
}
#editInline {
animation-name: fadeIn;
animation-duration: 1s;
background:#eee;
padding: 5px;
width: 100%;
}
.edit {
border-bottom: dotted 2px #eee;
padding-bottom: 5px;
border-left: solid #aaa 5px;
padding-left: 10px;
}
@keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
input {
width: 65%;
padding: 5px;
}
button {
padding: 5px;
margin-left: 5px;
}
JavaScript
class Forms {
constructor() {
this.saveBtnTxt1 = 'Guardar';
this.saveBtnTxt2 = 'Guardando ...';
this.closeBtn = 'Χ';
}
/**
* createForm()
* create temporal form
*/
createForm( id, method ) {
this.form = document.createElement('form');
this.form.setAttribute("id", id);
this.form.setAttribute('method', method);
this.edit.after(this.form);
}
/**
* createInput()
* create the field to edit text
*/
createInput( type, id, value ) {
this.input = document.createElement('input');
this.input.setAttribute('type', type);
this.input.setAttribute('id', id);
this.input.setAttribute('name', id);
this.input.setAttribute('minlength', '3');
this.input.value = value;
this.form.append(this.input);
}
/**
* createButton()
* create buttons
*/
createButton( id, value ) {
this.button = document.createElement("button");
this.button.innerHTML = value;
this.button.setAttribute('id', id);
this.input.after(this.button);
}
/**
* editInline()
* listen the event and create the form and its components
* @param object
*/
editInline( params ) {
let id = params.id;
this.edit = document.querySelector( '#'+params.id );
this.edit.addEventListener('click', (event) => {
let editInline = document.querySelector('#editInline');
if ( !editInline ) {
this.createForm( 'editInline', 'post' );
switch (params.type) {
case "text":
case "email":
case "search":
case "password":
case "tel":
case "url":
this.createInput( params.type, params.id, this.edit.innerHTML );
...