tags:

views:

42

answers:

2

I have an issue which I hope someone can help me with. I'm able to retrieve the text value of my checkbox. What I want to achieve is every time I click on a checkbox, it adds the text to the input with an id of "Selected". for example: if checkbox a, checkbox b, checkbox c are checked, I want to show "a, b, c". Instead what I'm getting are the text of the current one that is checked. Any help would be great.

$(document).ready(function(){
    $("#ListBox input").click(function() {
            var cbText = $(this).next().text();

            $('#Selected').val(cbText);    
        });
});
+2  A: 

It sounds like you want #Selected to have the text values for the currently selected checkboxes.

If that's right, try this: http://jsfiddle.net/nAACW/4/ (updated)

$(document).ready(function(){
    $("#ListBox input").click(function() {
        var cbText = $('#ListBox').find(':checked').next()
            .map(function() {
                return $.text([this]);
            }).get().join(', ');

        $('#Selected').val(cbText);    
    });
});​

EDIT: Changed to use $('#ListBox').find(':checked') instead of $(this).parent().find(':checked') as correctly suggested by @Felix Kling

patrick dw
+1 better than my answer because it works ;) But I would use `$("#ListBox").find(':checked')` because you don't know where those checkboxes are (`parent()` might not be the parent of all the boxes).
Felix Kling
@Felix - Very good point. I'll update. :o)
patrick dw
@patrick - Thanks, that seemed to do the trick. Instead of having $("#ListBox :checkbox"), I had to replace it with $("#ListBox input"). One question though patrick, my results came back as a,b,c ... how can I make it return a, b, c instead?@Felix - thanks to you too.
hersh
@hersh - I'll update my answer. Basically after `.get()`, you would do `.join(', ')`, since `.get()` gives you an array, and `.join()` will join the members of the array with whatever value you give it. Also, remember to click the checkbox next to this answer if it was helpful. :o)
patrick dw
@patrick - thank you so much!
hersh
A: 

Assuming your checkboxes have class='ListBox' (id should be unique, a class is used on more then one element), the code below will fill the input text field with the id of "Selected" with the text of all checkboxes of class 'ListBox' that are currently checked separated by commas.

var checks = new Array();
$(".ListBox input:checked").each(
  function(){checks.push($(this).text())}
)
$('#Selected').val(checks.join(','));
Adam