Simple edit-in-place by changing the type of an input

Christian Heilmann - Aug 8 '19 - - Dev Community

Making something editable in place is often the best way to have people make changes. Nobody wants to have 3 steps where one is enough. Take this example on CodePen. You can click the text, edit it and when you hit enter (or the enter button on a mobile) it goes back to being just a text.

The trick to make this happen is incredibly low effort. You start with a basic form:

<form>
  <input type="submit" value="edit me">
</form>

In order to make this editable without staying a form field, all you need to do is toggle the type of the input from "submit" to "search" when the form is submitted. Search as a type also offers the benefit of a delete button on Chromium based browsers.

const f = document.querySelector('form');
f.addEventListener('submit', (ev) => {
  let but = f.querySelector('input');
  but.type = (but.type === 'search') ? 'submit' : 'search';
  ev.preventDefault();
});

Nifty, isn't it?

Another way to do the same to any element is to toggle the contentEditable attribute as shown in the DIV of the example.

document.querySelector('div').
  addEventListener('click', (ev) => {
  let field = ev.target;
  field.contentEditable = field.contentEditable === true ? false: true;
});

However, editing these needs some knowledge as you need to focus on the next item to end editing. Or you need to code your own keyboard handling.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player