Created
May 22, 2012 02:14
-
-
Save johnallers/2766119 to your computer and use it in GitHub Desktop.
Add a suffix to an text input, which cannot be overwritten.
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
(function( $ ) { | |
$.fn.readOnlySuffix = function(suffix) { | |
return this.each(function() { | |
var $this = $(this), | |
suffixLength = suffix.length, | |
oldValue = suffix, | |
mouseIsDown = false; | |
// Must be a text input or text area | |
if (!($this.is(":text") || $this.tagName.toLowerCase() == "textarea")){ | |
return; | |
} | |
$this.val(suffix); | |
$this.keydown(function(evt){ | |
if (mouseIsDown){ | |
// Handle issue when cursor is dragged out of input and mouseup is not fired. | |
evt.preventDefault(); | |
$this.trigger("mouseup"); | |
return; | |
} | |
// Prevent keys that will delete the suffix | |
var inputLength = this.value.length, | |
offset = inputLength - suffixLength; | |
if ((evt.keyCode == 35 || evt.keyCode == 39 || evt.keyCode == 46) // Home, Right Arrow or Delete keys | |
&& this.selectionStart >= offset) { | |
evt.preventDefault(); | |
} | |
}); | |
$this.keyup(function(evt){ | |
// Prevent Select All | |
var offset = this.value.length - suffixLength, | |
actualStart = this.selectionStart > offset ? offset : this.selectionStart, | |
actualEnd = this.selectionEnd > offset ? offset : this.selectionEnd; | |
if (this.selectionStart != actualStart || this.selectionEnd != actualEnd){ | |
this.setSelectionRange(actualStart, actualEnd); | |
} | |
}); | |
$this.mousedown(function(evt){ | |
oldValue = $this.val(); | |
mouseIsDown = true; | |
}); | |
$this.mouseup(function(evt){ | |
var newValue = $this.val(), | |
offset = oldValue.length - suffixLength, | |
actualStart = this.selectionStart > offset ? offset : this.selectionStart, | |
actualEnd = this.selectionEnd > offset ? offset : this.selectionEnd; | |
mouseIsDown = false; | |
if (newValue != oldValue){ | |
$this.val(oldValue); | |
} | |
if (this.selectionStart != actualStart || this.selectionEnd != actualEnd){ | |
this.setSelectionRange(actualStart, actualEnd); | |
} | |
}); | |
}); | |
}; | |
})( jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's the license on this? This looks great.