loading...

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

codepo8 profile image Christian Heilmann ・1 min read

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.

Posted on by:

codepo8 profile

Christian Heilmann

@codepo8

Open Web guy at Microsoft and long-time JavaScript user

Discussion

pic
Editor guide
 

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?