Skip to content

Instantly share code, notes, and snippets.

@derblub
Forked from coreequip/jquery.readOnlySuffix.js
Created April 26, 2019 18:01
Show Gist options
  • Save derblub/102ef31869f08d6a46b75989556f4cae to your computer and use it in GitHub Desktop.
Save derblub/102ef31869f08d6a46b75989556f4cae to your computer and use it in GitHub Desktop.
(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.blur(function () {
if ($this.val().length == suffixLength) {
$this.val('');
}
});
$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();
if (oldValue == '') {
oldValue = suffix;
$this.val(suffix);
}
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