Apply Different Styles to Input Text Field When Empty (Using CSS)

Apply different styles to input text field when empty (using CSS)?

You could give the textfield the required attribute:

<input type="text" required />

and then check for validity with CSS:

input:invalid { background: green; }

or the opposite (only different for old browsers):

input:valid { background: blue; }

Applying a CSS style using JavaScript if text field is empty

I'm not sure if I fully understand your question but I've created test HTML file and that test works:

<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<style></style>
<script>
var styleAlreadyAppended = false;
function checkTextField(field) {
var sheet = document.styleSheets[0];
if (field.value == '' && styleAlreadyAppended !== true) {
sheet.insertRule("input:focus {background: #f30;}", 0);
styleAlreadyAppended = true;
}
else if (field.value != '' && styleAlreadyAppended === true) {
sheet.deleteRule(0);
}
}
</script>
</head>
<body>
<div>
<input id="testinput" type="text" value="">
<button onclick="checkTextField(document.getElementById('testinput'))">test</button>
</div>
</body>
</html>

Tested on FF36.

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";
}

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.

Change style of button element if text field is empty

Ok, you can add required to your input field like so:

<input id='textfield' required>
<input type="button" Value="Post" onClick="post()" id="postBtn">

And then, using :invalid and the adjacent sibling selector (+), you can style the button if the field is empty like so:

#textfield:invalid + #postBtn {
background-color: red;
}

Here is a fiddle of it in action: http://jsfiddle.net/w7377/

Note: If the text input field is not actually a required field, then this solution is not the way to go. You may have to use a Javascript solution if that's the case.

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.

Style empty textbox - CSS only solution

It is not possible to have a css only solution (as of now) for the updated post.

Sample Image

Edit CSS if Text Input empty on Submit

Here's a answer in pure JavaScript. I've written an event to check all the inputs when the form is submitted. If there are any values that are empty, then I update the class on the input and prevent the form from submitting.

var form = document.getElementById("login");login.addEventListener("submit", function(e) {  var valid = true;  var inputs = login.querySelectorAll("input");  [].forEach.call(inputs, function(input) {    if (input.value === "") {      valid = false;      input.classList.add("error");    }    });    if (!valid)    e.preventDefault();});
input[type=text], input[type=password], input[type=email] {  background-color: transparent;  border: none;  border-bottom: 1px solid #9e9e9e;  border-radius: 0;  outline: none;  height: 3rem;  width: 100%;  font-size: 1rem;  margin: 0 0 15px 0;  padding: 0;  box-shadow: none;  -webkit-box-sizing: content-box;  -moz-box-sizing: content-box;  box-sizing: content-box;  transition: all .3s; }
input[type=text]:focus:not([readonly]), input[type=password]:focus:not([readonly]), input[type=email]:focus:not([readonly]) { border-bottom: 1px solid #26a69a; box-shadow: 0 1px 0 0 #26a69a; }
input[type=text].error { border-bottom: 1px solid red;}
<form action="process.php" id="login" method="POST">  <p>Username: </p>  <div>    <input type="text" style="font-size: 13px; color: #7e7e7e;" autocomplete="off" id="user" name="user" maxlength="18" length="18">  </div>  <p>Password:</p>  <input type="password" name="pass" id="pass">  <p>Email:</p>  <input type="text" name="email">  <input type="hidden" name="fav_continent" value="Default">  <input type="hidden" name="fav_colour" value="Default">  <input type="hidden" name="subjoin" value="1">  <input type="submit" value="Register"></form>

How can I change an input style when I click submit and the inputs are empty?

That's not the correct way to do that, but you can try it.

Create an array to storage all errors.

$erros = array();

if($primeironome=="")
array_push( $erros, 'primeiro_nome');

if($ultimonome=="")
array_push( $erros, 'ultimo_nome');

After that, pass the array by parameter on method.

if( count( $erros ) > 0 ) {
ApresentarFormulario( $erros );
exit;
}

Check if there's a key with the input field.

function ApresentarFormulario( $erros ) {
// (...)

$class = ( in_array( 'primeironome', $erros ) ? 'erro' : '';
echo '<input type="text" name="primeironome" value="" class="' . $class . '" required>';

$class = ( in_array( 'ultimonome', $erros ) ? 'erro' : '';
echo '<input type="text" name="ultimonome" value="" class="' . $class . '" required>';

// (...)
}


Related Topics



Leave a reply



Submit