Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How should the code look? jQuery

Hi!

I wonder if theres a way I could use JQuery to make an input -box (in a form) have different background color if there is a value in it. (Even if it's not focused).

How should the code look in that case? Feel like I've tried everything...

Regards! :-)

/Emil

9 Answers

Here you go. Problem, other then a few syntax errors, was that the change method wasn't the right event listener. If it's blank and stays blank then there is no change. You needed to use the blur and focus event listeners. here is the code:

$(document).ready(function(){

     $("#name").on("focus blur", function(){

         if( $(this).val() != '') {
                  $(this).addClass('not-empty');    // update the class of the item
            }else{
                  $(this).addClass('empty');
            }
        });
});

Hi :-) Seems to work nice on codepen (except that the input doesnt go back to blue if i write something and then remove it), but not in my sublime text. Was it something else you changed except the jQuery-code?

Hi,

Depending on your scenario you could modify the input's css with addClass() method, of course before that you'd need to check the value in the input control using the .val() or .text() method of the jQuery object.

var control = $("#myInput");            //  find the item by id
if( $(control).val() === "hello") {      //  make the comparison
     $(control).addClass('helloClassCSSDesign');    // update the class of the item
}

Emil, you need to and an event listener in your JavaScript file so that JavaScript knows to continuously check the form field for changes in value. Try this code:

$(document).ready(function(){

     $("#name").change( function(){
           if( $(this).val() !=== "") {      //  make the comparison
                  $(this).addClass('namevalue');    // update the class of the item
            }else{
                  $(this).addClass('empty');
        });

Please check my comment below :-)

Emil, you must write separate css for each event class. Add all this code:

$(document).ready(function(){

     $("#name").change( function(){
           if( $(this).val() !=== "") {      //  make the comparison
                  $(this).addClass('not-empty');    // update the class of the item
            }else{
                  $(this).addClass('empty');
            }
        });
)};
#name{
    background-color: #5AADDD;
    border: #2A6B92 4px solid;
    color: #2A6B92;
    font-family: 'champagne__limousinesregular', sans-serif;
    font-size:20px;
    width: 200px;
    margin-bottom:20px;
    height:40px;
    border-radius: 10px;

    -webkit-transition-property: background;
        -webkit-transition-duration: 1s;
       -webkit-transition-timing-function: linear;
       -webkit-transition-delay: 0s;
}

#name.empty{
    background: #f0ad4e;
    color: #fff;
}

#name.not-empty{
    background: #5cb85c;
    color: #fff;
}

Copy Pasted all of that...Still not working..This is really weird...

is the site live or on your local host? If it's live please post the url, otherwise you may need to put it up on Codepen so that's it's easier for us to help you debug the problem.

http://codepen.io/EmilWallgren/full/Hcpgl/ Check it out :-) The form I'm trying to make this change to is at the bottom. The fade in-fade-out is supposed to be that way. But if there is text in any of the boxes, I want them to have a white background so that the user can see the text clear before they submit.

Hi Emil,

I have a codepen demo here of what I think you're trying to achieve: http://codepen.io/anon/pen/fxCsi

If an input has focus it will be white.

If an input doesn't have focus but has something in it then it will be white.

An empty out of focus input will be blue.

This should also work if the user empties a field that previously had something in it.

I didn't put prefixes on the transition property so you may not see a transition depending on what browser you're using.

Works on the pen but not on sublime text...Weird stuff goin' on...Is it possible that jQuery isnt working on localhost? That jQuery only works on a server?

GET file://code.jquery.com/jquery-1.11.0.min.js net::ERR_FILE_NOT_FOUND GET file://code.jquery.com/jquery-migrate-1.2.1.min.js net::ERR_FILE_NOT_FOUND Uncaught ReferenceError: $ is not defined jquery.js:1(anonymous function) jquery.js:1

these show up on the developer-tools, console... Is this normal since I personally dont have the files but are CDN ing them?

When working locally you have to put the http: in front of the // double forward slash.

Ok, now the only thing that seems to work is this $(document).ready(function(){

 $("#name").on("focus blur", function(){

     if( $(this).val() != '') {
              $(this).addClass('not-empty');    // update the class of the item
        }else{
              $(this).addClass('empty');
        }
    });

});

But it still doesnt go back to light-blue when I write something and then delete it and exit the box. Now I have a unfilled white box. :-) But still, it's muuuuch better

I don't know if this comment here was meant to be directed at Andrew Shook based on the code but it's not necessary to respond to the "focus" event and to have both a "not-empty" and "empty" class.

Also, if you put your scripts right before the closing </body> tag then you won't need to use $(document).ready()

Hi Jason :-) I solved the problem. Please read at the bottom of these comments :-)

Yes, I know you solved it. I was only confused on why you had posted Andrew's code as a comment to my answer.

You might want to post the solution you came up with so others reading this will know what it was.

Hi Jason :-)

Sorry for not being clear enough. I posted it to show that of all the answers I have gotten on this section, the only one that worked for me was the above posted. :-)

I just dont get it...

Look at my code. The first is from the form:

 <label for="name">Namn</label>
<input type="text" name="name" id="name">

The second is from my jQuery link:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/jquery.js"></script>

And the third is the code on a file related in a js folder on the same level as the html-file called js. (the file is called jquery.js)

$(document).ready(function(){

           var control = $("#name");            //  find the item by id

    if( $(control).val() !=== "") {      //  make the comparison
        $(control).addClass('namevalue');    // update the class of the item
            }
        });

This doesnt work. I created a class in my css file called .namevalue and set the background to white (the color I want the form to be (right now it's blue)).

What should I do? Is there something wrong with my code? Been trying this for 3 days now...

Regards :-)

/Emil

what is in your html file ? do you have the id field specified for the control ? you should have something like this:

<input type="text" id="my_input" placeholder="Enter text here please" />

and then in the javascript file:

$(document).ready(function(){
    var control = $("#my_input");            //  find the item by id

   if( $(control).text() != "") {      //  make the comparison - maybe we should use text(), not val()...
    $(control).addClass('namevalue');    // update the class of the item
  }
}

Hi again, none of you code work unfortunately :-/ I've added a css animation to the field (is this the thief in the drama, or is it irrelevant?)

Right now the css for the #name id looks like this:

    background-color: #5AADDD;
    border: #2A6B92 4px solid;
    color: #2A6B92;
    font-family: 'champagne__limousinesregular', sans-serif;
    font-size:20px;
    width: 200px;
    margin-bottom:20px;
    height:40px;
    border-radius: 10px;

    -webkit-transition-property: background;
        -webkit-transition-duration: 1s;
       -webkit-transition-timing-function: linear;
       -webkit-transition-delay: 0s;

FIXED IT!!!!

Thanks to all of you who have dedicated their time to help me! You are awesome! On the first days of the site being up I'll code a thank you statement to you guys! I'll notify you when it's up!

Have a fantastic day! And thank you for being awesome!

With sincere regard!!!

/Emil Wallgren

The solution was the following:

$(document).ready(function(){

 $("#name").on("focus blur",function(){

     if( $(this).val() != '') {
              $(this).addClass('not-empty');    // update the class of the item
        }else{
              $(this).removeClass('not-empty');
        }
    });

});