DEV Community

Christian Heilmann
Christian Heilmann

Posted on

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

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.

Discussion (3)

Collapse
maxart2501 profile image
Massimo Artizzu

I've never thought about changing the type of an input element, except for password field (click the πŸ‘οΈ eye button and you can see the password). Also it used to not work on older Internet Explorer but whatever...

But what about accessibility? Isn't this trick going to be confusing?

Collapse
jrop profile image
Jonathan Apodaca

Clever trick!