Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Create a switch statement from an if (jQuery)

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #45114
    Ricky55
    Member

    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”)

    #137359
    BaliBalo
    Participant

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

    #137510
    Ricky55
    Member

    Thanks mate I like the first option. Can I just insert this in place of my if statement?

    #137513
    BaliBalo
    Participant

    Yep, 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).

    #137561
    Ricky55
    Member

    Thanks really appreciate your time.

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.