2

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>
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.org/en/JavaScript/Guide Commented Apr 11, 2011 at 10:30

4 Answers 4

8

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks,Is values are adding to next index or same index?
No need to change [] to new Array
@user569125: list.push() will add the values to next index
0

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 ]

Comments

0

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.

Comments

0

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.

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.