Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if input placeholder is visible

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.

like image 800
Chase Avatar asked Feb 13 '16 21:02

Chase


2 Answers

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="">
like image 83
Bowser Avatar answered Oct 11 '22 18:10

Bowser


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

like image 40
Md Enzam Hossain Avatar answered Oct 11 '22 17:10

Md Enzam Hossain