pufAmuf
pufAmuf

Reputation: 7805

Button Switch case

I can't seem to get this to work in jquery. I am using this code as an alternative to having to define each button, however this does not work :/

http://jsfiddle.net/pufamuf/FV4jW/1/

Also, I was wondering if/how I can use more than one statement for each case. Thank you :)

Upvotes: 3

Views: 8319

Answers (4)

thecodeparadox
thecodeparadox

Reputation: 87073

$("input[type='button']").click(function() {
    switch (this.id) { 
    case 'buttonone':
        $("#content").html("Content changed");
        break;
    case 'buttontwo':
        $("#content").html("Content changed again");
        break;
    }
});

Upvotes: 3

daniels
daniels

Reputation: 19223

$("input[type='button']").click(function() {
    switch($(this).attr('id')) {
        case 'buttonone' : $("#content").html("Content changed"); break;
        case 'buttontwo' : $("#content").html("Content changed again"); break;
    }
});

You forgot the break after each case, had an extra )} at the end and also you need to use $(this).attr('id') instead of this.id

Upvotes: 1

CloudyMarble
CloudyMarble

Reputation: 37576

$("input[type='button']").click(function() {
    switch(this.id) {
        case 'buttonone' : 
            $("#content").html("Content changed");
            break;
        case 'buttontwo' : 
            $("#content").html("Content changed again");
            break;
    }
});

Upvotes: 1

hayesgm
hayesgm

Reputation: 9096

You need to add a break after each case in your switch statement. Updated JSFiddle here.

From Wikipedia:

break; is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block.

Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.

Updated Javascript:

 $("input[type='button']").click(function() {
   switch(this.id) {
     case 'buttonone': $("#content").html("Content changed"); break; //notice BREAK
     case 'buttontwo': $("#content").html("Content changed again"); break;
   }
 });

Upvotes: 5

Related Questions