5

As the title "Can I have multiple values in a single variable?"

First, I have got this form:

<form name="myform">
 <input type="text" name="mytext">
 <input type="button" onClick="clickButton()">
</form>

Then, take a look at my script.

<script>
function clickButton() {
  var x = document.myform.mytext.value;
  var a = 13;
  var b = 17;
  var c = 19;

  if (x == a) {
    alert('hello');
  } else if (x == b) {
    alert('hello');
  } else if (x == c) {
    alert('hello');
  } else {
    alert('goodbye');
  }
}
</script>

Is there any way to make one variable with multiple values? Like, var myvalues=1,2,3;

4
  • 5
    Use an array? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 20, 2014 at 8:31
  • No there is not such a variable. But you can use array or even object. Commented Dec 20, 2014 at 8:31
  • Another option would be using strings, you can enter in your textbox "1,2,3" and then in if statements look for those substrings Commented Dec 20, 2014 at 8:36
  • 2
    Why is this question voted up? Clearly no research made.. Commented Dec 20, 2014 at 8:38

3 Answers 3

4

The correct response to your question would be to use an array. But from what you're trying to do, Looks like your looking for an object, specifically the bracket notation:

function clickButton() {
  var x = document.myform.mytext.value,
    greetings = {
      "13": "hello",
      "17": "hello",
      "19": "hello"
    }
  alert(greetings[x] || "goodbye");
}
<form name="myform">
  <input type="text" name="mytext">
  <input type="button" onClick="clickButton()" value="greet">
</form>

Sign up to request clarification or add additional context in comments.

Comments

0

What you need here is an Array. An array is a variable that can hold mutiple values and/or elements. You can assign to it your values and then use the [n] selector where n is a number between 0 (first element) and 2 (in this case is 2 because you've only got 3 variables, so their positions will be 0, 1, 2).

Then, to make your code clearer, you can use the switch() statement to check the values and execute some code when a certain value is found.

Here is an example:

function clickButton() {
    var x = document.myform.mytext.value,
    values = [13, 17, 19];

    switch (x) {
        case values[0]:
        case values[1]:
        case values[2]:
            alert("hello");
            break;

        default:
            alert("goodbye");
            break;
    }
}

Comments

-1

use a object and give callbacks on values

  function abc(val){

      alert(val);
  }

 var doSomething = {
    "1": abc('1');,
    "2": abc('2');,
    "3": abc('3');
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.