最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Combining "ifthen..else" statement with "switch" statement - Stack Overflow

programmeradmin0浏览0评论

I have to display two numbers side by side (both starting off with a zero.gif file). Each number needs an input area for users to enter in a number between 1 and 5 and a button that says "Process Number," then the corresponding number should pop up.

I have to use an if-then-else statement for one and a switch statement for the other. I understand both of these separately but I'm not sure how to bine the two in the script code.

Currently, when I enter in a number in the first input box, both of them change at the same time. If I try the second box, I get the alert "You must choose a number between 1 and 5."

So I'm not sure how to separate the two. I used different image IDs but it's not working. Here's all the code.

<script type="text/javascript">
    function processNumber() {
      var numberInput = document.getElementById("userInput").value;

      // test for valid input number from 1 to 5
      if (numberInput < 1 || numberInput > 5) {
        alert("Your number must be from 1 to 5");
        return;

      }


      if (numberInput == 1)
        document.getElementById("ones").src="images/one.gif";
      else if (numberInput == 2)
        document.getElementById("ones").src = "images/two.gif";
      else if (numberInput == 3)
        document.getElementById("ones").src = "images/three.gif";
      else if (numberInput == 4)
        document.getElementById("ones").src = "images/four.gif";
      else if (numberInput == 5)
        document.getElementById("ones").src = "images/five.gif";
      else alert("Sorry - your input is not recognized");
      // likely a non numeric was entered if we got here


      switch (numberInput) {
        case "1": document.getElementById("group").src = "images/one.gif";
          break;
        case "2": document.getElementById("group").src = "images/two.gif";
          break;
        case "3": document.getElementById("group").src = "images/three.gif";
          break;
        case "4": document.getElementById("group").src = "images/four.gif";
          break;
        case "5": document.getElementById("group").src = "images/five.gif";
          break;

        default: alert("Sorry - your input is not recognized");

          // default in case a non numeric was entered
      } // end switch (numberInput)
    } // end function processNumber()

</script>

I have to display two numbers side by side (both starting off with a zero.gif file). Each number needs an input area for users to enter in a number between 1 and 5 and a button that says "Process Number," then the corresponding number should pop up.

I have to use an if-then-else statement for one and a switch statement for the other. I understand both of these separately but I'm not sure how to bine the two in the script code.

Currently, when I enter in a number in the first input box, both of them change at the same time. If I try the second box, I get the alert "You must choose a number between 1 and 5."

So I'm not sure how to separate the two. I used different image IDs but it's not working. Here's all the code.

<script type="text/javascript">
    function processNumber() {
      var numberInput = document.getElementById("userInput").value;

      // test for valid input number from 1 to 5
      if (numberInput < 1 || numberInput > 5) {
        alert("Your number must be from 1 to 5");
        return;

      }


      if (numberInput == 1)
        document.getElementById("ones").src="images/one.gif";
      else if (numberInput == 2)
        document.getElementById("ones").src = "images/two.gif";
      else if (numberInput == 3)
        document.getElementById("ones").src = "images/three.gif";
      else if (numberInput == 4)
        document.getElementById("ones").src = "images/four.gif";
      else if (numberInput == 5)
        document.getElementById("ones").src = "images/five.gif";
      else alert("Sorry - your input is not recognized");
      // likely a non numeric was entered if we got here


      switch (numberInput) {
        case "1": document.getElementById("group").src = "images/one.gif";
          break;
        case "2": document.getElementById("group").src = "images/two.gif";
          break;
        case "3": document.getElementById("group").src = "images/three.gif";
          break;
        case "4": document.getElementById("group").src = "images/four.gif";
          break;
        case "5": document.getElementById("group").src = "images/five.gif";
          break;

        default: alert("Sorry - your input is not recognized");

          // default in case a non numeric was entered
      } // end switch (numberInput)
    } // end function processNumber()

</script>
Share Improve this question edited Feb 7, 2016 at 2:10 Robin D. asked Feb 6, 2016 at 23:31 Robin D.Robin D. 979 bronze badges 4
  • You need two functions: processNumberIf and processNumberSwitch, one with ifs and another with switch. And one of them is used in one input box, another in another. – Serge Seredenko Commented Feb 6, 2016 at 23:35
  • Can you post your HTML? – Err Commented Feb 6, 2016 at 23:48
  • Err...yes, trying to figure out where to add the HTML on this page. Thanks! – Robin D. Commented Feb 7, 2016 at 2:08
  • @RobinD. You can edit your original question and include the HTML. – Err Commented Feb 7, 2016 at 7:34
Add a ment  | 

3 Answers 3

Reset to default 5

A simple solution can be an array of strings:

var numbers = ["zero", "one", "two", "three", "four", "five"];

if (numbers[numberInput] != undefined) {
   document.getElementById("ones").src = "images/" + numbers[numberInput] + ".gif";
   document.getElementById("group").src = "images/" + numbers[numberInput] + ".gif";
}
else 
   alert("Sorry - your input is not recognized");

I wanted to keep it clean, but this is just one of the solutions. If you use this a lot you can make a function.

You are missing the HTML which would really help remove some doubts about how your script is suppose to work. Based on your description alone, it sounds like you have two inputs, two images next those inputs defaulting to zero.gif, and two buttons next to those.

If that is correct, your HTML will look something like this:

<input type="text" id="one-val"> <img src="zero.gif" id="one-img">
<input type="button" id="one-btn" value="Process Number">
<br>
<input type="text" id="two-val"> <img src="zero.gif" id="two-img">
<input type="button" id="two-btn" value="Process Number">

Your description of the requirements is that you need if-then-else and switch to control the image switching based on the number entered. The below script works with the above HTML. The script is listening to any clicks on the button, when the button is pressed the below script runs based on which button you clicked. Button one is if-else-then and button two uses switch.

document.getElementById("one-btn").addEventListener("click", function(){
    var oneImg = document.getElementById("one-img");
    var oneVal = document.getElementById("one-val");
    if (oneVal.value == 1) {oneImg.src = "one.gif";}
    else if (oneVal.value == 2) {oneImg.src = "two.gif";}
    else if (oneVal.value == 3) {oneImg.src = "three.gif";}
    else if (oneVal.value == 4) {oneImg.src = "four.gif";}
    else if (oneVal.value == 5) {oneImg.src = "five.gif";}
    else {alert('Not an acceptable value.');}
});

document.getElementById("two-btn").addEventListener("click", function(){
    var twoImg = document.getElementById("two-img");
    var twoVal = document.getElementById("two-val");
    switch (twoVal.value) {
      case '1': twoImg.src = "one.gif"; break;
      case '2': twoImg.src = "two.gif"; break;
      case '3': twoImg.src = "three.gif"; break;
      case '4': twoImg.src = "four.gif"; break;
      case '5': twoImg.src = "five.gif"; break;
      default: alert('Not an acceptable value.');
    }
});

You can see this working on the following linked example: https://jsfiddle/9tfq781t/

I'm not totally sure what you need, so I'll take a guess.

Objective

  • Two inputs (left and right)
  • One button (labeled "Process Number")
  • 2 groups of 6 images (each one representing a number 0 to 5)
  • Required use of if-else if-else conditionals
  • Required use of switch statement
  • Sequence of expected behavior:
    • User enters a number into both inputs (must be: 0 > input < 6)
    • Clicking the button should make the 2 groups of 6 images display the image
      that corresponds to the value of the input. (ex. left input = 2 and right input = 4; so when the button is clicked, the left image should change into 2.png and the right image should change into 4.png.)

Solution

Trying to work within the parameters given was challenging since I wanted to do things differently (i.e. more efficiently).

  • Since there was a limit on input, I did it the lazy way and used number inputs (type="number" instead of the mon text inputs) and set the attributes min="1" and max="5".

  • Although the min and max attributes work, they only apply to the spinners. It's still possible to type in anything so some sort of validation must still be implemented.

  • The if-else if-else conditionals were used for validation.

  • If the inputs are acceptable, then each value is then processed through the function LED()

  • LED() is an eleven case switch statement that will change the 2 image groups according to the input values.

  • The 2 groups of 6 images is actually 1 sprite sheet (0-5.png) having 6 positions that's shared between two spans (#dex and #sin).

  • LED() uses the switch to manipulate #dex and #sin classes (.x-0 thru .x-5) which causes the changes in the sprite sheet (0-5.png).

The following is a stack snippet and there's a PLUNK as well.

var proc = document.getElementById('process');

proc.addEventListener('click', function(e) {
  var L = document.getElementById('left').value;
  var R = document.getElementById('right').value;
  if (isNaN(L)) {
    alert(L + 'is not a number');
  } else if (isNaN(R)) {
    alert(R + 'is not a number');
  } else if (R > 5 || L > 5) {
    alert('Input cannot exceed 5');
  } else if (R < 1 || L < 1) {
    alert('Input must be at least 1');
  } else {
    var D = 'D' + L.toString();
    var S = 'S' + R.toString();
    LED(D);
    LED(S);
  }
}, false);

function LED(x) {
  var dex = document.getElementById('dex');
  var sin = document.getElementById('sin');
  switch (x) {
    case 'D1':
      dex.classList.remove('x-0', 'x-2', 'x-3', 'x-4', 'x-5');
      dex.classList.add('x-1');
      break;
    case 'D2':
      dex.classList.remove('x-0', 'x-1', 'x-3', 'x-4', 'x-5');
      dex.classList.add('x-2');
      break;
    case 'D3':
      dex.classList.remove('x-0', 'x-1', 'x-2', 'x-4', 'x-5');
      dex.classList.add('x-3');
      break;
    case 'D4':
      dex.classList.remove('x-0', 'x-1', 'x-2', 'x-3', 'x-5');
      dex.classList.add('x-4');
      break;
    case 'D5':
      dex.classList.remove('x-0', 'x-1', 'x-2', 'x-3', 'x-4');
      dex.classList.add('x-5');
      break;

    case 'S1':
      sin.classList.remove('x-0', 'x-2', 'x-3', 'x-4', 'x-5');
      sin.classList.add('x-1');
      break;
    case 'S2':
      sin.classList.remove('x-0', 'x-1', 'x-3', 'x-4', 'x-5');
      sin.classList.add('x-2');
      break;
    case 'S3':
      sin.classList.remove('x-0', 'x-1', 'x-2', 'x-4', 'x-5');
      sin.classList.add('x-3');
      break;
    case 'S4':
      sin.classList.remove('x-0', 'x-1', 'x-2', 'x-3', 'x-5');
      sin.classList.add('x-4');
      break;
    case 'S5':
      sin.classList.remove('x-0', 'x-1', 'x-2', 'x-3', 'x-4');
      sin.classList.add('x-5');
      break;
    default:
      dex.classList.remove('x-1', 'x-2', 'x-3', 'x-4', 'x-5');
      dex.classList.add('x-0');
      sin.classList.remove('x-1', 'x-2', 'x-3', 'x-4', 'x-5');
      sin.classList.add('x-0');
      break;
  }
}
body {
  font: 400 16px/1.2'Consolas';
  color: lime;
  background: #444;
}
fieldset {
  width: 335px;
  border: 2px ridge lime;
}
input {
  text-align: center;
  font: inherit;
  color: lime;
  background: #000;
}
.x-0,
.x-1,
.x-2,
.x-3,
.x-4,
.x-5 {
  background: url(https://glpjt.s3.amazonaws./so/digit/0-5.png) no-repeat;
}
.x-0 {
  background-position: 0 0 !important;
  width: 18px;
  height: 24px;
}
.x-1 {
  background-position: 0 -25px;
  width: 18px;
  height: 24px;
}
.x-2 {
  background-position: 0 -50px;
  width: 18px;
  height: 24px;
}
.x-3 {
  background-position: 0 -75px;
  width: 18px;
  height: 24px;
}
.x-4 {
  background-position: 0 -100px;
  width: 18px;
  height: 24px;
}
.x-5 {
  background-position: 0 -125px;
  width: 18px;
  height: 24px;
}
#led {
  display: inline-table;
  width: 40px;
  object-fit: contain;
}
.digit {
  width: 18px;
  height: 24px;
  border: 1px inset #0F9;
  position: relative;
  top: -18px;
  z-index: 1;
  display: table-cell;
}
<form id="twoDigit" name="twoDigit">
  <fieldset>
    <legend>twoDigit</legend>

    <input id="left" name="left" type="number" min="1" max="5" step="1" />
    <input id="right" name="right" type="number" min="1" max="5" step="1" />

    <input id="process" name="process" type="button" value="Process Number" />

    <output id="led" name="led">
      <span id="dex" class="digit x-0"></span>
      <span id="sin" class="digit x-0"></span>
    </output>

  </fieldset>
</form>

发布评论

评论列表(0)

  1. 暂无评论