Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have multiple values in a single variable?

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;

like image 813
Anakin Avatar asked Oct 19 '22 20:10

Anakin


1 Answers

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>
like image 129
T J Avatar answered Oct 22 '22 09:10

T J