I'm trying to find a way to detect if an input is currently showing a placeholder.
I know we can test whether or not placeholders are supported in a given browser, which I would use, but that's not what I'm asking here.
The :placeholder-shown
pseudo class does exactly what I need, but the support for it is very low. Much lower than the support for placeholders in general. So I'm looking for an alternative method.
Note: The solution cannot rely on whether or not the input has changed or gained a value. Autofilled inputs neither have a technical value, nor have changed. Therefore the solution needs to truly detect the placeholder it'self.
First, check to see if the placeholder
attribute is being used by the element, and then check to see if the value of the input is empty:
function placeholderActive(selector) {
var el = document.querySelector(selector);
if (el.getAttribute('placeholder') && el.value === '') {
return true;
}
return false;
}
var a = placeholderActive('#test1'); // false
var b = placeholderActive('#test2'); // false
var c = placeholderActive('#test3'); // false
var d = placeholderActive('#test4'); // true
console.log(a, b, c, d);
<input id="test1" name="test1" value="123">
<input id="test2" name="test2" placeholder="" value="123">
<input id="test3" name="test3" placeholder="Some Placeholder" value="123">
<input id="test4" name="test4" placeholder="Another placeholder" value="">
Nowadays, for most browsers we can use :placeholder-shown
pseudo-class to detect whether placeholder is shown or not.
function placeholderActive(selector) {
return !!document.querySelector(selector + ':placeholder-shown');
}
const a = placeholderActive('#test1'); // false
const b = placeholderActive('#test2'); // false
const c = placeholderActive('#test3'); // false
const d = placeholderActive('#test4'); // true
console.log(a, b, c, d);
<input id="test1" name="test1" value="123">
<input id="test2" name="test2" placeholder="" value="123">
<input id="test3" name="test3" placeholder="Some Placeholder" value="123">
<input id="test4" name="test4" placeholder="Another placeholder" value="">
CSS-Tricks: https://css-tricks.com/almanac/selectors/p/placeholder-shown/
CanIUse: https://caniuse.com/#feat=css-placeholder-shown
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With