-4
// WORKING CODE [CODE1]
$('.enter-button').on('click', function (e) {
    e.preventDefault();
    var searchValue     = $('.a').val();
    var listOfLocations = $('.b').text().trim();
    var listSize        = $('.b ul li').size();
    if (listOfLocations.indexOf(searchValue) === -1) {
        switch (listSize) {
            case 0:
            case 1:
                $('.list-left').append('<li>' + searchValue + '</li>');
                break;

            case 2:
            case 3:
                $('.list-right').append('<li>' + searchValue + '</li>');
                break;
        }
    }
});

But I want it do this:

// CODE THAT I WANT IT TO RUN [CODE2]
$('.enter-button').on('click', function (e) {
    e.preventDefault();
    var searchValue     = $('.a').val();
    var listOfLocations = $('.b').text().trim();
    var listSize        = $('.b ul li').size();
    if (listOfLocations.indexOf(searchValue) === -1) {
        switch (listSize) {
            case (listSize <= 2):
                $('.list-left').append('<li>' + searchValue + '</li>');
                break;

            case (listSize >= 3):
                $('.list-right').append('<li>' + searchValue + '</li>');
                break;
        }
    }
});

Basically I want to run a range case on my switch statement, I looked through other stack overflow questions and they have said to do it like code 2. I haven't been able to get it to work so I'm trying to get some help! Aside from that, I'm also curious on why the case statement doesn't read it like CODE2.

Ben
  • 13
  • 3
  • Could you link the answers that recommended something like `case (listSize <= 2)`? – le_m May 19 '17 at 16:54
  • Do you really want switch case? Can you not use if/else which is more suitable here? – Pankaj Shukla May 19 '17 at 16:55
  • why you want switch case to work in that way? use simple if "else if" ladder. – Ranjit Singh May 19 '17 at 16:56
  • 1
    http://stackoverflow.com/questions/17145723/how-can-i-use-ranges-in-a-switch-case-statement-using-javascript – Ben May 19 '17 at 16:56
  • 1
    *they have said to do it like code 2.* No, they didn't. Read more closely. they used `switch (true)`. –  May 19 '17 at 16:56
  • I know I can use if else, but i'm just curious if it's possible to do what I stated above in JS – Ben May 19 '17 at 16:56
  • @Ben: switch is a strict compare, it can't work since you check 3 === true. If you really want this method, you have to change the switch to true – Djaevel May 19 '17 at 16:58

1 Answers1

3

It looks like you have a conditional for choosing either left or right based on size, you could break into so:

$('.list-' + ( listSize <=2 ? 'left' : 'right') ).append('<li>' + searchValue + '</li>');
fppz
  • 409
  • 2
  • 9