views:

42

answers:

3

I need to serialize a matched set so it's values can be passed to my rails app.

The matched set code is (returns the parent div of every uninitialized select element):

jQuery('select').filter(function(index){
     return jQuery(this).val() == 0;}).closest('div')

for serialization I really only need the id of each matched element so I tried:

jQuery('select').filter(function(index){
     return jQuery(this).val() == 0;}).closest('div').attr('id')

Unfortunatly attr() only works on the first element in a matched set.

Since the resulting javascript will be sent via rails' remote_function :with I believe javascript can only be one statement.

How can a matched set be serialized, or to-string'd?

A: 
var result = [];

jQuery('select').filter(function(index){
  return jQuery(this).val() == 0;
}).closest('div').each( function() {
  result.push(this.id);
});

var resultStr = result.join(',');
Tomalak
+2  A: 

For variety's sake, here's an answer using map:

result = jQuery('select')
    .filter( function(index){
        return jQuery(this).val() == 0;
    })
    .closest('div')
    .map( function(){
        return this.id;
    })
    .get()       // stop here if you want an array
    .join(',');  // or here if you want a string
Ken Redler
+1  A: 

For even more variety's sake, here's one with less looping involved:

var idString = $('select').map(function(){
    var select = $(this);
    return select.val() == 0 ? select.closest('div').attr('id') : null;
}).get().join(',');
J-P