Sven
Sven

Reputation: 13296

jQuery switch-case not working, syntax issue?

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 $.

Upvotes: 0

Views: 2820

Answers (3)

Devin Burke
Devin Burke

Reputation: 13820

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

Upvotes: 1

fivedigit
fivedigit

Reputation: 18682

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.');

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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;
    }
});

Upvotes: 1

Related Questions