Note that there are some explanatory texts on larger screens.

plurals
  1. POStyling HTML inputs differently based upon their values using either CSS or jQuery
    primarykey
    data
    text
    <p>I have an HTML form with plenty of inputs, most of which are optional. I want to apply different CSS to inputs based on their values as I think this will make it easier to see what fields have been specified.</p> <p>For example, if a textbox actually has a value entered, I'd like it to have a different background/border colour. I'm not sure how I'd write a CSS selector that tests for this (nor how many browsers would support it.)</p> <p>Similarly I have some radio buttons where one option is 'none', but if any other option is selected, its label text should be bold.</p> <p>Ideally I'd do this with CSS, but if it required jQuery, then that's ok, especially if it would give better crossbrowserness.</p> <p><strong>EDIT</strong> Some great answers here -- looks like JS is the path here. Reading through these JS solutions I realise some requirements that would have been neatly addressed by CSS:</p> <ul> <li>The form may be presented partially populated (when the entity is edited), meaning that no 'change' event fires.</li> <li>The form is dynamic in that new text boxes may be added.</li> </ul> <hr> <p>In the end I went for an amalgam of the below answers, which I'll include here in case someone else finds it useful:</p> <pre><code>var highlightInput = function () { var $this = $(this); if ($this.is(':text') || $this.is('textarea')) { $this.toggleClass('has-value', this.value.length &gt; 0); } else if ($this.is(':radio') || $this.is(':checkbox')) { $this.parent().find('input[name="' + this.name + '"]').each(function () { var $label = $('label[for="' + this.id + '"]'); var isSelected = this.checked &amp;&amp; $label.text() != 'Unspecified'; $label.toggleClass('selected-option', isSelected); }); } }; $('textarea, input:text').live('keyup', highlightInput) .live('change', highlightInput) .each(highlightInput); $('input:radio, input:checkbox').live('change', highlightInput) .each(highlightInput); </code></pre> <p>And some CSS, with crazy colours as placeholders:</p> <pre><code>input[type=text].has-value, textarea.has-value { background-color:#0F0; } label.selected-option { background-color:#0F0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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