tags:

views:

73

answers:

2

I have made an each statement which iterates through each class item found. At the same time there is another item with a different class but has the same key. I am needing to get the key from the first each and put it into the 2nd item without having to loop a second time.

$('.searchby').each(function(k,v){ // looping through .searchby
 $(v).live('change',function(){ // when .searchby drop down changed do this
  selv = $(this).val(); // get value of drop down
  $.post('file.php',{ 'val' : selv },function(data){

   // Below is where I need what I need to happen.
   // Previously I had .searchby as id but need multiple.
   // So, what I need it to do is like php.
   // $('.searchfield[k]).html(data); // <-- like this

   $('#searchfield').html(data);


  },'html'); // html, xml, script, json
 });
});

--EDIT--

First, the v in $(v).live should be $(this).live 2nd, I am wanting to convert the single/id pull script to a multi pull script. So, I wrote this which works.

$('.searchby').each(function(k,v){
 $(this).change(function(){
  selv = $(this).val();
  $.post('file.php',{
   'val' : selv
  },function(data){
   $('.searchfield').each(function(kk,vv){
    if(k == kk) $(vv).html(data);
   });
   //$('#searchfield').html(data);
  },'html'); // html, xml, script, json
 });
});

But I would like to be able to take the inner .each out and replace it with:

$('.searchfield:eq('+k+')') <-- something like this if I can get it to work

So the solution is this:

$('.searchby').each(function(k,v){
 $(this).change(function(){
  selv = $(this).val();
  $.post('file.php',{
   'val' : selv
  },function(data){
   $('.searchfield:eq('+k+')').html(data);
  },'html'); // html, xml, script, json
 });
});

Thanks everyone

A: 

The question is not clear. You talk of classes, but then your code uses $('#searchfield'), which is used to select elements with the given ID.

Assuming you really want to select elements with a given class (which is more correct, as there should not be elements with duplicated ID), and if there are exactly one element with class searchfield for each elements selected by $.each(), then you can use $($('.searchfield')[k]).html(data).

kiamlaluno
If I remember correctly, `$(...)[k]` returns the DOM element, not a jQuery object, so you would have to write `$($(...)[k]).html()` instead.
Victor Nicollet
You are correct, Victor.
kiamlaluno
A: 

I suspect your $(v)above is incorrect, because $(...).each() provides its callback with a single documented argument (the index).

To achieve the equivalent of $('.searchfield[k]'), there's an actually quite close syntax available:

$('.searchfield:eq('+k+')')
Victor Nicollet
I put this code into my code and gave the final version in the top post.
David