views:

41

answers:

2

Hello, I would like to update multiple elements(with different values) from the same selector. What would be the easiest way to go about doing this? I have tried

$(document).ready(function(){
  var t=$('.test input');
  t[0].val('Foo');
  t[1].val('Bar');
});

with this HTML

<div class="test">
    <input type="text">
    <input type="text">
</div>

A live example is here http://jsbin.com/afoda/6

I get an error though for undefined t[0].val is not a function. What is the proper way to access multiple elements like this?

+4  A: 

You can use .eq(index) to get .val(), like this:

$(document).ready(function(){
  var t=$('.test input');
  t.eq(0).val('Foo');
  t.eq(1).val('Bar');
});

You can test it here, .eq() get the jQuery object representing the element at that index, rather than the DOM element. This approach also works (if you're sticking to inputs, it wouldn't work the same for example on a <select> element):

$(document).ready(function(){
  var t=$('.test input');
  t[0].value = 'Foo';
  t[1].value = 'Bar';
});

You can test that here

Nick Craver
A: 

When you are accessing the elements in a jQuery object by index, you don't get a new jQuery object with each element, you just get the element. If you want to use the val method you need to create a jQuery object for each element:

$(document).ready(function(){
  var t = $('.class input');
  $(t[0]).val('Foo');
  $(t[1]).val('Bar');
});

Another way is to loop through the elements and get values from an array:

$(document).ready(function(){
  var values = ['Foo', 'Bar'];
  $('.class input').each(function(i){
    $(this).val(values[i]);
  });
});
Guffa