webdad3
webdad3

Reputation: 9080

javascript array with element ids

I have loaded an array in javascript with a select amount of input element ids on the form. Some of the input elements are radio buttons & checkboxes,.

What I would like to do is something jQuery where I'm looping through my array and passing in the id like this:

for(i = 0; i <= myArray.length - 1;i++){
alert($(myArray[i].val());
}

I'm getting an error when I do this. Is there a way to do what I want?

UPDATE:

My array contains the IDs of the elements. My elements have numeric values as their IDs. For example in my array #50:0 and #51:0 are elements of the array.

My HTML looks like this:

<input id="50:0" type="radio" value="1" name="50:0">Yes
<input id="50:0" type="radio" value="2" name="50:0">No

<input id="51:0" type="checkbox" value="1" name="51:0">Option 1
<input id="51:0" type="checkbox" value="2" name="51:0" >Option 2
<input id="51:0" type="checkbox" value="3" name="51:0" >Option 3

Assume that you clicked Yes and Options 1 & 3 I need those values...

Upvotes: 0

Views: 691

Answers (2)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

You forgot a closing parenthesis.

alert($(myArray[i]).val());

And make sure that you strings are #foo and not just foo.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630419

Your syntax is a little off, it should be this:

for(i = 0; i < myArray.length; i++){
  alert($(myArray[i]).val());
}

The $(selector) was missing it's closing ). Also make sure your elements in the array are prefixed with a #, otherwise you'll need $('#' + myArray[i]) instead, to make it an #ID selector.

And a readability tip, you can replace i <= myArray.length - 1 with just i < myArray.length.

Upvotes: 3

Related Questions