Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could make it so that only elements that have a certain class on them <em>and</em> are required, are pink. Add an event handler to each required element that adds that class when you leave the element.</p> <p>Something like:</p> <pre><code>&lt;style&gt; input.touched:invalid { background-color: pink; color: white; } input.touched:valid { background-color: white; color: black; } &lt;/style&gt; &lt;script&gt; document.addEventListener('DOMContentLoaded', function() { var required = document.querySelectorAll('input:required'); for (var i = 0; i &lt; required.length; ++i) { (function(elem) { function removeClass(name) { if (elem.classList) elem.classList.remove(name); else elem.className = elem.className.replace( RegExp('(^|\\s)\\s*' + name + '(?:\\s+|$)'), function (match, leading) {return leading;} ); } function addClass(name) { removeClass(name); if (elem.classList) elem.classList.add(name); else elem.className += ' ' + name; } // If you require a class, and you use JS to add it, you end up // not showing pink at all if JS is disabled. // One workaround is to have the class on all your elements anyway, // and remove it when you set up proper validation. // The main problem with that is that without JS, you see what you're // already seeing, and stuff looks hideous. // Unfortunately, you kinda have to pick one or the other. // Let non-blank elements stay "touched", if they are already, // so other stuff can make the element :invalid if need be if (elem.value == '') addClass('touched'); elem.addEventListener('blur', function() { addClass('touched'); }); // Oh, and when the form submits, they need to know about everything if (elem.form) { elem.form.addEventListener('submit', function() { addClass('touched'); }); }; })(required[i]); } }); &lt;/script&gt; </code></pre> <p>And of course, it won't work as is in IE8 or below, as (a) <code>DOMContentLoaded</code> is relatively new and wasn't standard when IE8 came out, (b) IE8 uses <code>attachEvent</code> rather than the DOM-standard <code>addEventListener</code>, and (c) IE8 isn't going to care about <code>:required</code> anyway, as it doesn't technically support HTML 5.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload