Home › Forums › JavaScript › Create a switch statement from an if (jQuery)
- This topic is empty.
-
AuthorPosts
-
June 3, 2013 at 12:56 pm #45114Ricky55Member
Hi,
I have this jQuery that I’m using for a login with PHP. All working fine but I now have more options to add, I believe that using a switch statement would be better than adding more and more if’s.
Can anyone help me create this switch statement I’m still learning jQuery and what I’ve done so far has broken the script.
Cheers
Richard
[My code pen have I linked this correctly](http://cdpn.io/toBgc “Codepen”)
June 3, 2013 at 1:37 pm #137359BaliBaloParticipantHi.
You can do it this way:switch(response)
{
case ‘standard’:
window.location.href = “/client-area/”;
break;
case ‘worldstores’:
window.location.href = “/client-area/worldstores/”;
break;
case ‘wilko’:
window.location.href = “/client-area/wilko/”;
break;
default:
$(“#message”).html(“Sorry your username or password was entered incorrectly.”);
}(I removed the p tag in the error message because the formatting was messed up)
But there are other ways to do it:var urls = {
standard: ‘/client-area/’,
worldstores: ‘/client-area/worldstores/’,
wilko: ‘/client-area/wilko/’
};
if(response in urls)
window.location.href = urls[response];
else
$(‘#message’).html(‘Sorry your username or password was entered incorrectly.’);Do what you think is the more understandable.
June 3, 2013 at 6:30 pm #137510Ricky55MemberThanks mate I like the first option. Can I just insert this in place of my if statement?
June 3, 2013 at 6:43 pm #137513BaliBaloParticipantYep, put this instead of this previous block:
if(response==’standard’)window.location.href=”/client-area/”;
if(response==’worldstores’)window.location.href=”/client-area/worldstores/”;
if(response==’wilko’)window.location.href=”/client-area/wilko/”;
else $(“#message”).html(“Sorry your username or password was entered incorrectly.”);Talking about that, it should have been this:
if(response==’standard’)window.location.href=”/client-area/”;
else if(response==’worldstores’)window.location.href=”/client-area/worldstores/”;
else if(response==’wilko’)window.location.href=”/client-area/wilko/”;
else $(“#message”).html(“Sorry your username or password was entered incorrectly.”);(with the else before every if) otherwise it would show the error if the response is not ‘wilko’ (even if it’s ‘standard’ for example).
June 4, 2013 at 4:26 am #137561Ricky55MemberThanks really appreciate your time.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.