0

Why is this switch-case not working? I've tried every possible syntax, but it is just not working. Or is a switch-case the wrong method in this case?

jQuery('#main input').blur(function() {
    switch(jQuery(this).attr('name') {
        case 'email':
            jQuery(this).val('That's you e-Mail adress.');
            break;
        case 'nickname':
            jQuery(this).val('That's your nickname.');
            break;
    }
});

Please note: I am using jQuery in non conflict mode, that's why I use jQuery instead of $.

oers
  • 18,436
  • 13
  • 66
  • 75
Sven
  • 12,997
  • 27
  • 90
  • 148
  • You're missing a `)`. Use a tool like JSLint or JSHint to find problems like this. – Andrew Whitaker Jan 11 '12 at 22:17
  • Backticks (`) should be used for inline code. If you want to post multiple lines, please highlight the code and then click the curly braces button. It'll format it for easier reading. – Brandon Jan 11 '12 at 22:17
  • Thank you, will do it like that in the future. – Sven Jan 11 '12 at 22:20
  • Welcome to Stack Overflow, Sven! If you see an answer below that helps you, you should upvote it. Don't forget to *accept* the answer (if any) that best answers your question by clicking the large checkmark to the left of that question. :) – Devin Burke Jan 12 '12 at 14:55

3 Answers3

1

You have two types of errors:

  1. You are missing a parenthesis ) closing around the switch parameter.
  2. You are not escaping your apostrophes (') in the word "that's".

Corrected Code:

jQuery('#main input').blur(function() {
    switch(jQuery(this).attr('name')) { // Added a )
        case 'email':
            jQuery(this).val('That\'s you e-Mail adress.'); // Escaped the '
            break;
        case 'nickname':
            jQuery(this).val('That\'s your nickname.'); // Escaped the '
            break;
    }
});

Update:

If you are unfamiliar with escaping strings in JavaScript (such as with the word That's above), take a look at this Stack Overflow question: Escaping Strings in JavaScript

Community
  • 1
  • 1
Devin Burke
  • 13,642
  • 12
  • 55
  • 82
1

Using many ' in the same line seems to mess your syntax. change as below,

jQuery('#main input').blur(function() {
    switch(jQuery(this).attr('name')) {  // <-- fix 1: added closing )
        case 'email':
            jQuery(this).val("That's you e-Mail adress."); // <-- fix 2: quotes 
        break;
        case 'nickname':
            jQuery(this).val("That's your nickname.");  // <-- fix 3: quotes 
            break;
    }
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
1

You have several errors in here:

switch(jQuery(this).attr('name') {

Missing a closing parenthesis. Should be:

switch(jQuery(this).attr('name')) {

You should escape the quote in this string:

jQuery(this).val('That's you e-Mail adress.');

Like this:

jQuery(this).val('That\'s you e-Mail adress.');
fivedigit
  • 18,464
  • 6
  • 54
  • 58