views:

422

answers:

7

Here is my code in which i generate comma separated string to provide a list of id to the query string of another page and i get the comma at the end of string.

<script type="text/javascript">
    $(document).ready(function() {
        $('td.title_listing :checkbox').change(function() {
            $('#cbSelectAll').attr('checked', false);
        });
    });
    function CotactSelected() {
        var n = $("td.title_listing input:checked");
        alert(n.length);
        var s = "";
        n.each(function() {
            s += $(this).val() + ",";
        });
        window.location = "/D_ContactSeller.aspx?property=" + s;
        alert(s);
    }
</script>

I Need to remove this last comma. Can anyone tell me how to remove that. Thanks in Advance.

+4  A: 
s = s.substring(0, s.length - 1);
Amarghosh
+1  A: 

You could use 'normal' javascript:

var truncated = str.substring(0, s.length - 1);
The MYYN
+3  A: 

You can use the String.prototype.slice method with a negative endSlice argument:

n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"

Or you can use the $.map method to build your comma separated string:

var s = n.map(function(){
  return $(this).val();
}).get().join();

alert(s);
CMS
Ah, beat me to it
Justin Johnson
+10  A: 

Use Array.join

var s = "";
n.each(function() {
    s += $(this).val() + ",";
});

becomes:

var a = [];
n.each(function() {
    a.push($(this).val());
});
var s = a.join(', ');
Sam Doshi
+1 ... way better than all this substring fumbling.
Filburt
+1  A: 

Instead of removing it, you can simply skip adding it in the first place:

var s = '';
n.each(function() {
   s += (s.length > 0 ? ',' : '') + $(this).val();
});
Guffa
I must say this is a neat trick! +1
o.k.w
The way tried to solve is better but it doesn't work at all.
Sanju
@Sanju: What happens when you try to use it? Do you get any error message?
Guffa
Actually it doesn't worked without any error message.I have done it by the way i was doing earlier.
Sanju
@Sanju: What do you mean by "doesn't work"? What happens, and how does that differ from what you expect?
Guffa
A: 

A more primitive way is to change the each loop into a for loop

for(var x = 0; x < n.length; x++ ) {
  if(x < n.length - 1)
    s += $(n[x]).val() + ",";
  else
    s += $(n[x]).val();
}
o.k.w
A: 

Sam's answer is the best so far, but I think map would be a better choice than each in this case. You're transforming a list of elements into a list of their values, and that's exactly the sort of thing map is designed for.

var list = $("td.title_listing input:checked")
    .map(function() { return $(this).val(); })
    .get().join(', ');

Edit: Whoops, I missed that CMS beat me to the use of map, he just hid it under a slice suggestion that I skipped over.

Joel Mueller