var arr = $(".producttypeid");
var premiumtypecodes = Array(arr.length);
for (var i = 0; i < arr.length; i++)
premiumtypecodes[i] = arr[i].value;
The above code does not seem to work. The intent is to assign the output to an array. Anything that I am missing.
Why this simple code does not work? Reasoning would be highly appreciated….
Based on the feedback I am adding sample markup and adding details to make my intent unambigous.
<input class="producttypeid" type="hidden" value="512">
I want to extract the value from all tags using style producttypeid and make an array
Here’s how I’d do it:
That assumes all of the matching elements are
inputelements (because of the use ofvalue). If some of them may betextareaorselectelements, then change the line inside the iterator function to:If they’re not form fields at all, you’ll have to define what you mean by their “value” (e.g., you might use
$(this).text()to get their text content, or$(this).html()to get their markup, or something else entirely).I’m not immediately seeing any problem with your version other than that you’re missing an
iaftervar:Other than that, it should have worked, but note that although
Array(arr.length)works, the usual way to write it isnew Array(arr.length)(and there’s no need to pre-set the length; JavaScript arrays aren’t really arrays so you don’t get the usual benefit of doing that).