Skip to content

Instantly share code, notes, and snippets.

@deenoize
Created January 11, 2016 18:42
Show Gist options
  • Save deenoize/ae3f172ebe3192e23228 to your computer and use it in GitHub Desktop.
Save deenoize/ae3f172ebe3192e23228 to your computer and use it in GitHub Desktop.
Make inputs editable and able to save edited value after blur or enter-press
<ul id="checklist">
<li class="edit">
<span>Apples</span>
<input value="Apples" />
</li>
<li class="">
<span>Oranges</span>
<input value="Oranges" />
</li>
</ul>
var checklist = document.getElementById("checklist");
var items = checklist.querySelectorAll("li");
var inputs = checklist.querySelectorAll("input");
for (var i = 0; i < items.length; i++) {
items[i].addEventListener("click", editItem);
inputs[i].addEventListener("blur", updateItem);
inputs[i].addEventListener("keypress", itemKeypress);
}
function editItem() {
this.className = "edit";
var input = this.querySelector("input");
input.focus();
input.setSelectionRange(0, input.value.length);
}
function updateItem() {
// change span value to entered value and delete ".edit"
this.previousElementSibling.innerHTML = this.value;
this.parentNode.className = "";
}
function itemKeypress(event) {
// enter press code = 13
if (event.which === 13) {
// run updateItem with this value
updateItem.call(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment