views:

100

answers:

5

Hello all,

I have this function below which returns all IDs of checked boxes on my page seperated by a comma. It works great but the problem is, it seems to put a lot of white space after each checkbox ID. I can't seem to figure out why?

/*Returns selected checkbox ID in string seperated by comma */
function get_selected_chkbox(){

    var checked_string = '';

     $('#report_table').find("input[type='checkbox']").each(function(){

        if(this.checked){

            checked_string = checked_string + this.id + ',';

        }

    });

            alert(checked_string);//test1         ,test2            ,   

    return checked_string;
}

Thanks all for any help

+2  A: 
rahul
@Rahul - I still need to find where the spaces are coming from but I'll be using your function, much cleaner.
Abs
+1  A: 

Use this to get rid of the white spaces :)

http://api.jquery.com/jQuery.trim/

$.trim(checked_string);

Tim
+1  A: 

I would guess that the spaces are in the html.

Try (with a nod to @rahul's answer):

return $.makeArray($('#report_table input:checkbox:checked').map(function(){
  return $.trim($(this).attr('id'));
})).join(',');

(And, it appears, a nod to @Tim's answer!)

wombleton
I'm pretty sure that with the map function on a wrapped set that you can skip the parameters to the callback and simply use 'this' in place of el.
steve_c
You're quite right! I also needed to makeArray it as it's not a real array.
wombleton
+1  A: 

please add your html code for the checkbox. It may possible you write

<input type="checkbox" id="test1        "/>
Salil
A: 

or this.id.replace(/^\s+|\s+$/g, '') would work

Martyn