I’ve got a form with 5 search criteria input boxes on it. I received an additional requirement to have a "Clear All" button on the page to clear the input boxes.
I would like to have the "Clear All" button actually be a div with a background image that has a gray background when the input boxes are empty, and has a red background when they have something in them.
Clicking on the "Clear All" button will clear the input boxes.
I’ve gotten almost everything working, except for the toggle to the red background image when the user types something in the search boxes. I built a jsfiddle: http://jsfiddle.net/pJgyu/27896/ that shows my problem (I used background-color, instead of a background-image, to eliminate unnecessary stuff).
The JavaScript in my jsfiddle matches what I want to do, and looks like this:
function clearSearchClick() {
$('.ui-clear').removeClass('enabled').addClass('disabled');
$(':input').val('');
$('.first').focus();
}
function docKeyPress(event) {
if (event.which === 13) {
event.preventDefault();
alert('pretend I searched');
}
}
function searchEmpty() {
var valid = true;
$(':input').each(function() {
if ($(this).val() !== '') return false;
});
return valid;
}
function inputKeyUp(event) {
if (!searchEmpty()) {
$('ui-clear.disabled').removeClass('disabled').addClass('enabled');
}
}
$(function () {
$('.first').focus();
$('.ui-clear').click(clearSearchClick);
$(':input').keyup(inputKeyUp);
$(document).keypress(docKeyPress);
});
I know the following about the JavaScript:
- The
.firstfocus works - The
.ui-clearclick handler works
I’m not getting the black box to the left of the first search box to turn red when the user types something. I would appreciate any insight on correct, efficient ways to accomplish this goal.
I think you may be over-complicating things…
If I understand things correctly, you want the appearance of a div (based on an applied class) to change if any inputs in a form contain user entered text?
You also want to do this on a keyup event rather than a change?
So, I’d do something like this
First set the default (black) background in the class that is applied to the div
and a class for ‘enabled’
That’s really all you need in styles to make this work
Then the code – again, keep it simple
What are we doing here?