views:

28

answers:

3

Hello,

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.

+1  A: 

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.

Dave
I setup an example here: http://jsfiddle.net/wVeCc/
Jannis
Ah, hadn't refreshed the page before posting my Fiddle… many thanks! This works wonderfully.
Jannis
Glad I can help :-)
Dave
A: 

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));
  });
});
xar
Thanks for this solution. I am using the once Dave gave me for this project but it's good to know that .push will work equally well. Thanks.
Jannis
A: 

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+']'));
})
Peter Ajtai