I modified the script for you on jsbin.com so you can see how it might work with the switch. Basically, you need to concatenate the variable, otherwise it will be treated as a string. Also, using id (not formattedID) for that variable is sufficient.

I'd do it differently, though. Since the three squares are siblings and they all have class="button", you could do this:

$(document).ready(function(){

        $(".button").click(function(){
$(this).css("background-color", "blue").siblings(".button").css("background-color", "green");
                $("#test").append("clicked id = " + this.id + "<br />");
        });
});

Here's another jsbin.com URL:

http://jsbin.com/eluli/edit


--Karl

____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com




On Oct 28, 2009, at 3:39 AM, alexpls wrote:


I'm a beginner to programming, so please bear with me, I might be
missing something really obvious here and not realising it.
For my first jQuery script that I'm writing unassisted by a tutorial,
I want to make a very simple page.
This page has three squares on it, and once you click on a square it
changes to blue while the other two squares change to green.
To avoid code repetition, and give myself a bit of a challenge I
decided to use the switch statement, and have implemented it like
this:

$(document).ready(function(){

        $(".button").click(function(){
                var id = "#" + $(this).attr("id");

                switch(id){
                        case id:
                                var formattedID = "\'" + id + "\'";
                                $(".button:not(formattedID)").css("background-color", 
"green");
                                $("#test").append("formattedID = " + formattedID + "<br 
/>");
                        break;
                };

        });

});

What seems to make this code not work is the :not statement. If I
replace the ":not(formattedID)" with ":not('#button1')" the code works
as expected. I don't understand why the :not() works with a string
that's directly typed into it, but not with a variable that holds a
string.

I've uploaded this to JS Bin, so you can see the code fully.

http://jsbin.com/ibate/edit

Any help is very appreciated,

alexpls

Reply via email to