JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" value="Some text here..." class="populated-text">
<input type="text" value="Any default text you like" class="populated-text">
<input type="text" value="Will be used as empty" class="populated-text">
CSS
.grayed
{
color: #aaaaaa;
}
JavaScript
jQuery(function ($) {
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
// Removes the defualt text on key press
function keyDown (e) {
var input = $(e.target);
if (input && !input.data('data-entered')) {
input.data('data-entered', true);
input.removeClass('grayed');
input.val("");
}
}
// Restore the default text if empty on blur
function blur(e) {
var input = $(e.target);
if (input && input.val() === "") {
input.data('data-entered', false);
input.addClass('grayed');
input.val(input.data('blank-value'));
}
}
// Sets the caret position to the start or end on focus
function focus (e) {
var input = $(e.target), len;
if (input) {
if (!input.data('data-entered')) {
// focus at the start if data not entered
input.selectRange(0,0);
} else {
// focus at the end if text is entered
len = input.val().length;
input.selectRange(len, len);
}
}
}
// Sets the caret to the start if the empty text is displayed
function mouse (e) {
var input = $(e.target);
if (input && !input.data('data-entered')) {
input.selectRange(0,0);
}
}
$('.populated-text').each(function () {
var input = $(this);
...