0

This function replicates the user experience of a Select/MultiSelect dropdown element - displaying the values of checkboxes checked in a container (adds/removes them when they're checked/unchecked), and if more than 3 items have been checked it displays the # selected instead of the values selected.

It's a combination of 2 functions and they're not playing well together when items are unchecked (i.e. it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)

I think it would be much better if I used an array to store the values, adding/removing values from the array when items are checked/unchecked, and I know how do to in PHP but not in Javascript. This code should create the array, but I can't figure out how to integrate it into my code.

$('input:checkbox[name="color[]"]:checked').each(function () {
     selectedColors.push($(this).val());
});

Existing Code:

JS

$(".dropdown_container ul li").click(function () {
    var text = $(this.children[0]).find("input").val();
    var text_edited = text.replace(/_/g, " ");
    var currentHtml = $(".dropdown_box span").html();
    var positionLocation = currentHtml.indexOf(text_edited);
    var numberChecked = $('input[name="color[]"]:checked').length;

    if (positionLocation < 1) {
        if (numberChecked <= 3) {
            $(".dropdown_box span").html(currentHtml.replace('Colors', ''));
            $(".dropdown_box span").append(', ' + text_edited);                                
            } else {
                $(".dropdown_box span").html(currentHtml.replace(currentHtml, numberChecked + " Selected"));
            }                                                            
    } else {
        (currentHtmlRevised = currentHtml.replace(text_edited, ""));
        $(".dropdown_box span").html(currentHtmlRevised.replace(currentHtml)); 
    }                
});

HTML

<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
    <ul id="select_colors">
        <li>
            <label><a href="#"><div style="background-color: #ff8c00" class="color" onclick="toggle_colorbox_alt(this);"><div class=CheckMark>&#10003;</div>
            <input type="checkbox" name="color[]" value="Black" class="cbx"/>
            </div>Black</a></label>
        </li>
        <!-- More List Items --!>
    </ul>
</div>

2 Answers 2

0

Easiest to just replace the entire content each time. Also use the change event instead of the click event.

$(".dropdown_container input").change(function () {
    var checked = $(".dropdown_container input:checked");
    var span = $(".dropdown_box span");
    if (checked.length > 3) {
       span.html("" + checked.length + " selected");
    }
    else {
        span.html(checked.map(function () { return $(this).val().replace("_"," "); }).get().join(", "));
    }
});

Example: http://jsfiddle.net/bman654/FCVjj/

8
  • I think it's probably missing something because it's not displaying any values in ".dropdown_box span" Commented Mar 7, 2013 at 5:18
  • Oops I did not see that the text was in the parent label. I corrected the example and added a jsFiddle.
    – Brandon
    Commented Mar 7, 2013 at 5:25
  • It works perfectly :-D One question – How would I modify it to the equivalent of 'var text = $(this.children[0]).find("input").val();'? I'd simplified the code snippet because I hadn't realized that it would matter, but I'm using this with hidden checkboxes so I also need it to encompass another <div> inside the <li>. I know that it can be tough to read code in these comment boxes, so I updated the question with the complete <li> code. Commented Mar 7, 2013 at 6:07
  • 1
    You want the value of the checkbox instead of the label text? In my code snippet above, replace $(this).parent().text() with $(this).val(). The map call is iterating over the checkbox input elements so within that function this is the actual input element. I suppose you want to replace _ with ` ` also, so it would be return $(this).val().replace("_", " ");
    – Brandon
    Commented Mar 7, 2013 at 13:29
  • I updated the answer and demo with this change. Please mark as Answer if this helps you out :)
    – Brandon
    Commented Mar 7, 2013 at 13:36
0

try this:

    $('.cbx').change(function(){
      var cbx = $('.cbx:checked');
      var str = '';

      if (cbx.length<=3 && cbx.length!=0){
        for (var i=0;i<cbx.length;i++){
          if (i>0) str += ', ';
          str += cbx[i].value;
        }
     } else if (cbx.length==0){
       str = 'Colors';
     } else {
       str = cbx.length;
     }
     $('.dropdown_box span').html(str);
   });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.