Created
January 11, 2016 18:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul id="checklist"> | |
<li class="edit"> | |
<span>Apples</span> | |
<input value="Apples" /> | |
</li> | |
<li class=""> | |
<span>Oranges</span> | |
<input value="Oranges" /> | |
</li> | |
</ul> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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