JSFiddle - React, Tailwind, and code Playground
HTML
<form action="/echo/html/">
<p><input placeholder="Your name" name="name" value="" />
<input placeholder="email@example.com" name="email" value="myemail@example.com" />
<input type="submit" value="Submit" /></p>
</form>
<p class="output">USING NATIVE PLACEHOLDER, THIS DEMO WILL NOT WORK!!</p>
<script>
if ( ! ('placeholder' in document.createElement('input'))) {$('.output').text('USING JAVASCRIPT PLACEHOLDER');}
$('form').submit(function (e) {
e.preventDefault();
$('.output').text($(this).serialize());
$.post('/echo/html/', {html: $(this).serialize()}, function (data) {
alert(data);
}, 'html');
});
</script>
<ul>
<li>Make sure to try submitting email@example.com, in reality it should work.</li>
</ul>
CSS
[placeholder]{color:green}/* Actual input */
.placeholder{color:red}/* Placeholder text */
JavaScript
// Don't bother if the browser already supports it
if ( ! ('placeholder' in document.createElement('input'))) {
$('[placeholder]').each(function() {
var self = $(this);
// Attribute name, used as class name too for convenience.
var p = 'placeholder';
// Don't apply to inputs with an initial value.
self.data('empty', self.val() == '');
self.focus(function() {
// Input not modified by the user, and has the placeholder as the value.
if (self.data('empty') && self.val() == self.attr(p)) {
self.val('').removeClass(p);
}
})
.blur(function() {
// Input was not modified and is empty.
if (self.data('empty')) {
self.val(self.attr(p)).addClass(p);
}
})
.change(function() {
// On change, apply data("empty") to field if the user has modified the value, and it is empty.
self.data('empty', self.val() == '');
});
// Apply the placeholder.
if (self.val() == '' || self.val() == self.attr(p)) {
self.val(self.attr(p)).addClass(p);
}
});
// Forms should NOT submit placeholder values.
$('form:has([placeholder])').bind('submit', function () {
$(this).find('[placeholder]').each(function () {
// If value not modified, and is the placeholder value
if ($(this).data('empty')) {
// Unset the value (placeholder text). <-- not working
$(this).val('');
}
});
});
}