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.
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.)
Similarly I have some radio buttons where one option is 'none', but if any other option is selected, its label text should be bold.
Ideally I'd do this with CSS, but if it required jQuery, then that's ok, especially if it would give better crossbrowserness.
EDIT 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:
- The form may be presented partially populated (when the entity is edited), meaning that no 'change' event fires.
- The form is dynamic in that new text boxes may be added.
In the end I went for an amalgam of the below answers, which I'll include here in case someone else finds it useful:
var highlightInput = function () {
var $this = $(this);
if ($this.is(':text') || $this.is('textarea')) {
$this.toggleClass('has-value', this.value.length > 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 && $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);
And some CSS, with crazy colours as placeholders:
input[type=text].has-value, textarea.has-value { background-color:#0F0; }
label.selected-option { background-color:#0F0; }