Search code examples
javascriptcheckboxreturn-valueselected

Modify this function to display all the checked checkboxes' values (instead of last selected)


I am replicating the functionality of a select/multiselect element and I'm trying to use this function to display the items which have been selected in the relevant container. I need to show all the values that have been selected in a comma-separated list, but it's currently only showing one selection (the last one made). It's also displaying the checkbox, background color, etc. of the list item selected instead of the checkbox value (i.e. value="Black").

I'm using this for a few multiselect form elements where I couldn't use the jQuery UI MultiSelect Widget because they needed to be styled in a very specific way (options displayed with background colors or images and spread out over several columns, etc.).

I've included the relevant code below, and I've posted a working example of the styled 'faux'-multiselect element here: http://jsfiddle.net/chayacooper/GS8dM/2/

JS Snippet

$(document).ready(function () {
    $(".dropdown_container ul li a").click(function () {
        var text = $(this).html();
        $(".dropdown_box span").html(text);
    });
    function getSelectedValue(id) {
        return $("#" + id).find("dropdown_box span.value").html();
    }
});

HTML Snippet

<div class="dropdown_box"><span>Colors</span></div>

<div class="dropdown_container">
<ul>
<li><a href="#"><div style="background-color: #000000" class="color" onclick="toggle_colorbox_alt(this);" title="Black"><div class=CheckMark>&#10003;</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/></div>Black</a>
</li>
<!-- More list items with checkboxes -->
</ul>
</div>

I've tried several other methods (including many of the ones listed here: How to retrieve checkboxes values in jQuery), but none of those worked with hidden checkboxes and/or the other functions I need to incorporate in these particular form elements.


Solution

  • well, to start with change click(..){..} in document.ready to

    $(".dropdown_container ul li a").click(function () {
        var text = $(this).html();
        var currentHtml = $(".dropdown_box span").html(); 
        var numberChecked = $('input[name="color[]"]:checked').length;
        $(".dropdown_box span").html(currentHtml.replace('Colors','')); 
        if (numberChecked > 1) { 
            $(".dropdown_box span").append(', ' + text); 
            } else { 
            $(".dropdown_box span").append(text); 
        }
    });
    

    this will do the appending of text right. however I couldn't understand the handling of images in the code.

    Update, to handle just the value: replace var text = $(this).html(); with

    var text = $(this).find("input").val();