Is there a way to detect whether the input box has text through CSS? I tried using the :empty pseudo-class and [value=""] without success. I can't seem to find a solution.
I guess it must be possible, considering we have pseudo-classes like :checked and :indeterminate which are similar things.
Please note: I am doing this for a "Stylish" style and cannot use JavaScript.
Also note that Stylish is used on a page that the user has no control over, client-side.
You can use
:placeholder-shownpseudo-class. Technically, a placeholder is required, but you can use a space instead.input:not(:placeholder-shown) { border-color: green; } input:placeholder-shown { border-color: red; }StylishCan't do this because CSS doesn't make it possible.CSS has no (pseudo) selectors for
values.See::emptyThe selector only applies to child nodes, not to input values.[value=""]canwork; but only in theinitialstate. This is because the node'svaluepropertyseen by CSS is different from the node'svalueproperty(changed by the user or DOM JavaScript, and submitted as form data).Unless you only care about the initial state,youmustuse a user script or a Greasemonkey script.Fortunately, this is not difficult. The following script will work in Chrome, or in Firefox with Greasemonkey or Scriptish installed, or in any browser that supports userscripts (i.e. most browsers, except IE).
See a demonstration of CSS limitations and JavaScript solutions onthis jsBin page.
// ==UserScript== // @name _Dynamically style inputs based on whether they are blank. // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @grant GM_addStyle // ==/UserScript== /*- The @grant directive is needed to work around a design change introduced in GM 1.0. It restores the sandbox. */ var inpsToMonitor = document.querySelectorAll ( "form[name='JustCSS'] input[name^='inp']" ); for (var J = inpsToMonitor.length - 1; J >= 0; --J) { inpsToMonitor[J].addEventListener ("change", adjustStyling, false); inpsToMonitor[J].addEventListener ("keyup", adjustStyling, false); inpsToMonitor[J].addEventListener ("focus", adjustStyling, false); inpsToMonitor[J].addEventListener ("blur", adjustStyling, false); inpsToMonitor[J].addEventListener ("mousedown", adjustStyling, false); //-- Initial update. note that IE support is NOT needed. var evt = document.createEvent ("HTMLEvents"); evt.initEvent ("change", false, true); inpsToMonitor[J].dispatchEvent (evt); } function adjustStyling (zEvent) { var inpVal = zEvent.target.value; if (inpVal && inpVal.replace (/^\s+|\s+$/g, "") ) zEvent.target.style.background = "lime"; else zEvent.target.style.background = "inherit"; }