1

So I have some fields like this:

[1] [2] [3] with attributes: name=item1,item2,item3 and class = item

What I want to do is get all three fields into an array:

so:

array = [1,2,3];

Is there a way to do this using the unique class attribute: "item" ?

3 Answers 3

2

You can use Array.map() method to return an array out of attribute:

var items = $('.item').attr('name').split(','), // convert to array
  arr = [].map.call(items, function(value) { // use 
    return +value.match(/\d/)[0]; // return the number value from the array "items"
  });

$('pre').html(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p name='item1,item2,item3' class='item'>item</p>
<pre></pre>

Sign up to request clarification or add additional context in comments.

Comments

1

try this $(".items").toArray() to get the same result, possibly one that works.

Comments

1

Get the items and loop through them. Adding each one to your list.

var items = [];
$('.item').each(function(index, value){
  //where value is an input
  items.push(value);
});

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.