Jannis
Jannis

Reputation: 17375

jQuery: Looping over elements writing their ID attribute to an array?

I'm trying find a bunch of <label>s in a form of mine based on an array of elements and their id attribute.

eg. [ input#country , input#other-country ] would be able to find <label for="country"> , <label for="other-country"> and so on…

so far I have this code:

var LOCATION = {};

LOCATION.option = form.find('input[name=location]').toArray();
LOCATION.labels = [
    $.each( LOCATION.option, function(i, input) {
        $('label[for='+input.id+']');
    })
];

When logging out the input.id inside the $.each loop I get the correct value being written out however I can't seem to find a way to write my matched label element from inside the $.each loop into the LOCATION.labels array afterwards.

Does anyone know how to put them into the array? toArray() does not seem to work either…

Thanks for reading.

Upvotes: 1

Views: 368

Answers (3)

Peter Ajtai
Peter Ajtai

Reputation: 57715

You almost had it, just .push() from inside .each()

var LOCATION = {};

LOCATION.option = form.find('input[name=location]').toArray();
LOCATION.labels = [];

$.each( LOCATION.option, function(i, input) {
    LOCATION.labels.push($('label[for='+input.id+']'));
})

Upvotes: 0

xar
xar

Reputation: 1439

Try this one out. Not really a one line solution to get directly the array, but I've tested this and it works fine.

var LOCATION = {};
$(function(){
  var form = $("#form"); //sample form
  LOCATION.option = form.find('input[name=location]').toArray();
  LOCATION.labels = [];
  $.each(LOCATION.option, function(i,input) {        
    LOCATION.labels.push($('label[for='+input.id+']').get(0));
  });
});

Upvotes: 0

DMI
DMI

Reputation: 7191

I'd probably use .map():

var LOCATION = {};

LOCATION.option = form.find('input[name=location]').toArray();
LOCATION.labels = $.map( LOCATION.option, function(input) {
  return $('label[for='+input.id+']').get(0);
});

See here for an example of this in action.

Upvotes: 1

Related Questions