JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<form action="">
<div>
<input placeholder="empty" value="" />
</div>
</form>
</body>
JavaScript
(function ($) {
// Selektor erzeugen
var selector = [];
$.each(["input", "textarea"], function (index, nodeName) {
if (!("placeholder" in document.createElement(nodeName))) {
selector.push(nodeName + "[placeholder]");
}
});
selector = selector.join(",");
// Event-Handler
function showPlaceholder() {
// this bezieht sich auf ein DOM-Element
if (this.value === "") {
this.value = this.getAttribute("placeholder");
}
}
function hidePlaceholder() {
// this bezieht sich auf ein DOM-Element
if (this.value === this.getAttribute("placeholder")) {
this.value = "";
}
}
function hideAllPlaceholders() {
// this bezieht sich auf das Formular, das abgeschickt werden soll
$(this).find(selector).each(hidePlaceholder);
}
// Plugin definieren
$.fn.placeholder = function () {
// this bezieht sich auf ein jQuery-Objekt
var elements = this.filter(selector);
// alle Elemente initialisieren
elements.each(showPlaceholder);
// Event-Handler registrieren
elements.on({
"focus" : hidePlaceholder,
"blur" : showPlaceholder
});
elements.closest("form").on({
"submit" : hideAllPlaceholders
});
return this;
};
}(jQuery));
// get input value ...
console.log('input value without polyfill: "' + $('input').val()+'"');
// init polyfill
$('input').placeholder();
// get input value again ...
console.log('input value with polyfill: "'+ $('input').val()+'"');