views:

310

answers:

2

Hi,

I have the following text input on a budget calculator form which displays the final balance...

<tr><td align="right"><b>Balance: &pound;</b></td><td align="left"><input type="text" class="res" name="res" id="res" size="10" readonly="readonly"></td></tr>

How do I go about setting the background of the input to red using css and jquery if the value is a negative number?

I am sure this is very simple but I have scanned the net looking for a solution for ages.

Please can someone help?, my head hurts!

+2  A: 
$('input').blur(function () {
    $(this).toggleClass('redBackground', $(this).val() < 0);
});

Set a class redBackground to give your inputs red background and it should work fine.

CSS:

input.redBackground {
    background-color: red;
}
RaYell
But use better class names. Aim to describe content not presentation. I'd use "negativeValue" rather than "redBackground". It will only bite you if you change the style to be red on white, or to use italics, or something else in the future.
David Dorward
Thanks, this works. However, only after you have hit 'calculate' and click your cursor into the text field. How could it be done so that it changes colour on the input being updated?
Dan C
+1  A: 

You can use the .bind to attach a onkeyup event to it.

$(document).ready(function(){
$('.res').bind('keyup', function() { 

if($('.res').val() < 0){
 $('.res').css({'background-color':'#FF0000'});
}});
});
SteD
If you are using anonymous event handler then instead of using `$(selector).bind(eventname)` use `$(selector).eventname`. It's the same but your code readability will be improved.
RaYell