Matching an Empty Input Box Using Css

CSS apply style to empty inputs ([value=''])

Searched css style empty inputs and found the following:

Matching an empty input box using CSS

You need to use JavaScript.

To use the CSS style, you would have to type in the attribute: value='' in your HTML, but then the CSS would match regardless of if the value changes mid-session.

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

Stylish cannot do this because CSS cannot do this. CSS has no (pseudo) selectors for <input> value(s). See:

  • The W3C selector spec
  • The Mozilla/Firefox supported selectors
  • Cross-browser, CSS3 support table

The :empty selector refers only to child nodes, not input values.

[value=""] does work; but only for the initial state. This is because a node's value attribute (that CSS sees), is not the same as the node's value property (Changed by the user or DOM javascript, and submitted as form data).

Unless you care only about the initial state, you must use a userscript or Greasemonkey script. Fortunately this is not hard. The following script will work in Chrome, or Firefox with Greasemonkey or Scriptish installed, or in any browser that supports userscripts (i.e. most browsers, except IE).

See a demo of the limits of CSS plus the javascript solution at this 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";
}

Is there a CSS selector that checks if an input has any text in it?

you can try this code

    input:not(:placeholder-shown) {
border-color: green;
}

How can I highlight optional input:text if it isn't empty?

Note: If you're targeting modern browsers and using a placeholder (or you can use a placeholder), you can use Irina's :placeholder-shown pseudo-class below rather than .empty) and do away with the JavaScript. It doesn't work in IE or Edge v44 or earlier, but works in all up-to-date modern browsers. But: You can use -ms-input-placeholder for IE and Edge v44 and earlier, making the JavaScript part of the below defunct. But I don't want to edit it to use :placeholder-shown and :-ms-input-placeholder because that duplicates Irina's answer (somewhat), and I can't remove this answer because it's accepted. See the end of the answer for an example, though.


I found solution for :required inputs but nothing for :optional.

Two ways you can do that:

  1. You can use :not(:required). :not is the negation pseudoclass. It accepts a simple selector and inverts its meaning. "Not required" is "optional."

  2. You can style all of the inputs in the "optional" way, then override that styling for :required elements.

Unfortunately, though, the "empty" part of your question can't be answered with CSS alone for input elements that are optional (more here).

Here's an example of #1, using JavaScript to add/remove a class when the input is/isn't empty:

"use strict";function toggleEmptyClass(el) {    if (el.tagName === "INPUT") {        // If you need IE compatibility, you'll need an `if`/`else`;        // IE doesn't support the second argument for `toggle`        el.classList.toggle("empty", !el.value);    }}document.querySelectorAll("input").forEach(toggleEmptyClass);document.addEventListener("input", function() {    toggleEmptyClass(event.target);});
input:not(.empty):required {    background-color: #FF8000;}input:not(.empty):not(:required) {    background-color: #0080FF;}
<div>    <label>        Required:        <input type="text" required value="required">    </label></div><div>    <label>        Required and (initially) empty:        <input type="text" required>    </label></div><div>    <label>        Optional:        <input type="text" value="optional">    </label></div><div>    <label>        Optional and (initially) empty:        <input type="text">    </label></div>

apply styles to empty input/textarea only

From what I can see, :empty is still a working draft and may not be supported by the specific browser you are using.

A quick JavaScript solution would be to add/remove an HTML class based upon whether or not the textarea has a value.

.empty{/*styles go here*/}

And your JavaScript:

textareaElement.addEventListener('input',function(){
if(this.value && this.classList.contains("empty")) this.classList.remove("empty");
else this.classList.add("empty");
},false);

More info about Element.classList can be found on MDN.

Selecting empty text input using jQuery

Another way

$('input:text').filter(function() { return $(this).val() == ""; });

or

$('input:text').filter(function() { return this.value == ""; });

or

// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK! 
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to @AaronLS
$('input:text[value=""]');

Working Demo

code from the demo

jQuery

 $(function() {

$('#button').click(function() {

var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
var string = "The blank textbox ids are - \n";

emptyTextBoxes.each(function() {
string += "\n" + this.id;
});
alert(string);
});

});

:not(:empty) CSS selector is not working?

Being a void element, an <input> element is considered empty by the HTML definition of "empty", since the content model of all void elements is always empty. So they will always match the :empty pseudo-class, whether or not they have a value. This is also why their value is represented by an attribute in the start tag, rather than text content within start and end tags.

Also, from the Selectors spec:

The :empty pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness;

Consequently, input:not(:empty) will never match anything in a proper HTML document. (It would still work in a hypothetical XML document that defines an <input> element that can accept text or child elements.)

I don't think you can style empty <input> fields dynamically using just CSS (i.e. rules that apply whenever a field is empty, and don't once text is entered). You can select initially empty fields if they have an empty value attribute (input[value=""]) or lack the attribute altogether (input:not([value])), but that's about it.



Related Topics



Leave a reply



Submit