Created
September 12, 2011 15:34
-
-
Save wesen/1211569 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| $.fn.makeInputToggle = function () { | |
| this.each(function () { | |
| var $this = $(this); | |
| if ($this.data("inputToggled")) { | |
| /* avoid double input toggle handling */ | |
| return; | |
| } | |
| /* click on the previous text span or element */ | |
| $this.hide().prev().click(function () { | |
| /* hide other input toggles */ | |
| $(".inputToggle").not($this).cancelToggle(); | |
| $(this).hide(); | |
| /* show the following input field */ | |
| $this.show().select().focus(); | |
| }); | |
| /* cancel editing when losing focus */ | |
| $this.focusout(function () { | |
| $this.cancelToggle(); | |
| }); | |
| if (($this.is("input") && (($this.attr("type") === "text") || | |
| ($this.attr("type") === "password"))) || | |
| ($this.is("textarea"))) { | |
| /* if input is a text input, check for enter/escape or tab key */ | |
| $this.keydown(function (l) { | |
| switch (l.keyCode) { | |
| case 13: // enter, save the value | |
| $this.updateToggle(); | |
| break; | |
| case 27: // escape, revert the value | |
| $this.cancelToggle(); | |
| break; | |
| } | |
| return false; | |
| }); | |
| } else if ($this.is("select")) { | |
| /* if it's a select list, use the text value of the selected option instead of the value. */ | |
| $this.change(function () { | |
| var newVal = $(this).find("option:selected").text(); | |
| $(this).hide().prev().text(newVal).show(); | |
| return false; | |
| }); | |
| } else { | |
| /* else replace text with the value */ | |
| $this.change(function () { | |
| var newVal = $(this).val(); | |
| $(this).hide().prev().text(newVal).show(); | |
| return false; | |
| }); | |
| } | |
| /* tab, cycle through inputToggle fields (shift+tab for invert cycle) */ | |
| $this.keydown(function (l) { | |
| if (l.keyCode == 9) { | |
| $this.updateToggle(); | |
| var idx = $(".inputToggle").index($this) + (l.shiftKey ? -1 : 1); | |
| var len = $(".inputToggle").length; | |
| if (idx >= len) { | |
| idx = 0; | |
| } else if (idx < 0) { | |
| idx = len - 1; | |
| } | |
| var nextToggle = $(".inputToggle:eq(" + idx + ")"); | |
| nextToggle.show().select().focus().prev().hide(); | |
| } | |
| return false; | |
| }); | |
| $this.data("inputToggled", true); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment