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;
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;
- 5 Use an array? developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – therealrootuser Commented Dec 20, 2014 at 8:31
-
No there is not such a variable. But you can use
array
or evenobject
. – sadrzadehsina Commented Dec 20, 2014 at 8:31 -
Another option would be using strings, you can enter in your textbox
"1,2,3"
and then inif
statements look for those substrings – frogatto Commented Dec 20, 2014 at 8:36 - 2 Why is this question voted up? Clearly no research made.. – Chrillewoodz Commented Dec 20, 2014 at 8:38
3 Answers
Reset to default 4The 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>
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;
}
}
use a object and give callbacks on values
function abc(val){
alert(val);
}
var doSomething = {
"1": abc('1');,
"2": abc('2');,
"3": abc('3');
}