user569125
user569125

Reputation: 1463

javascript global array

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>

Upvotes: 2

Views: 54269

Answers (4)

Town
Town

Reputation: 14906

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.

Upvotes: 0

RoToRa
RoToRa

Reputation: 38421

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.

Upvotes: 0

Kevin
Kevin

Reputation: 5694

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 ]

Upvotes: 0

Sangeet Menon
Sangeet Menon

Reputation: 9915

Change 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
}

Upvotes: 8

Related Questions