I am having below html code and trying to add new values to global array by onchanging of javascript function.I am trying to do like below way.But it is giving javascript errors.Please suggest anyone how to do this.
<html>
<head>
<script>
var list=[];
function getList(value){
list=list(value);
}
</script>
</head>
<body>
<tr>
<td>
<select name="test" onchange="getList(this)">
<option id="1" value="one">One</option>
<option id="2" value="two">two</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="test1" onchange="getList(this)">
<option id="3" value="three">three</option>
<option id="4" value="four">four</option>
</select>
</td>
</tr>
</body>
</html>
I am having below html code and trying to add new values to global array by onchanging of javascript function.I am trying to do like below way.But it is giving javascript errors.Please suggest anyone how to do this.
<html>
<head>
<script>
var list=[];
function getList(value){
list=list(value);
}
</script>
</head>
<body>
<tr>
<td>
<select name="test" onchange="getList(this)">
<option id="1" value="one">One</option>
<option id="2" value="two">two</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="test1" onchange="getList(this)">
<option id="3" value="three">three</option>
<option id="4" value="four">four</option>
</select>
</td>
</tr>
</body>
</html>
Share
Improve this question
asked Apr 11, 2011 at 10:27
user569125user569125
1,46313 gold badges29 silver badges40 bronze badges
1
-
How about telling us what the error is? Is the function
list
defined somewhere (I guess not)? I suggest you read a JavaScript tutorial first: developer.mozilla/en/JavaScript/Guide – Felix Kling Commented Apr 11, 2011 at 10:30
4 Answers
Reset to default 8Change your Javascript
to the following
var list=new Array; ///this one way of declaring array in javascript
function getList(value){
list.push(value);//push function will insert values in the list array
}
Adding values to an array is quite simple, all you have to do is call the push(..)
method.
Like so:
var list = [ ];
list.push(1);
console.info(list); // Outputs: [ 1 ]
- Mozilla array reference
- Mozilla array push reference
The easiest way to add a value to an array in JavaScript, it to use the push
method (unless you need to support IE5):
function getList(value) {
list.push(value);
}
Two things:
In your case this would add references to the select elements to the list. That's most likely not what you want. What exactly do you want to add?
getList
isn't really a suitable name for that.addToList
would be probably better.
You're currently passing the entire select element to your function, rather than the selected value. You can pass the selected value like this:
getList(this.options[this.selectedIndex].value)
Then you can use list.push(value)
in your function to add the selected value to your array.