Change input field color based on value

Discussion in 'Scripts' started by rybussell, Dec 16, 2011.

to remove all ads.
  1. rybussell

    rybussell New Member

    Messages:
    3
    I guess as my first post, I should do a little intro. My name is Ryan. I'm 27 and from Michigan. Been into web design since I was about a freshman in high school. Stopped doing it for a while and am now getting back into it. A huge college football fan (go bucks) and baseball (go tribe!).

    Anyway, I think it's an easy script but I can't figure it out. I'm still quite basic when it comes to the more advanced coding.

    I have a page of about 40 input fields. What I am looking for is a script that will change the background color of the input field based on the value. Example, if the field is blank, the background remains white. If someone writes the word "OK" in it, I want it to turn green. If they write "NO" in it, I want it to turn red. I figure this is a jQuery thing which I've not studied yet. Any help would be appreciated!

    Ryan
     
  2. conor

    conor New Member

    Messages:
    348
    Hi Ryan,

    jQuery makes things like this very easy. You could try something like this:

    Code:
    // this means execute when the page has loaded
    $(function(){
    
      // add an event trigger, which executes this function
      // when someones typing in an input
      $( 'input' ).keyup( function( ){
        var $this = $( this ); 
    
        // get the value of the input and switch between
        // its possible values, changing the color if it matches
        // ok or no. 
        var val = $this.val( );
        switch( val ){
          case "OK":
            $this.css( { "background-color" : "green" } );
          break;
          case "NO":
            $this.css( { "background-color" : "red" } );
          break;
          default:
            $this.css( { "background-color" : "#fff" } );
         }
      });
    });
    
    Hope that helps, let me know if you have any questions.
     

Share This Page