此函数复制了 Select/MultiSelect 下拉元素的用户体验 - 显示容器中选中的复选框的值(在选中/取消选中时添加/删除它们),如果选中了 3 个以上的项目,则显示 #选择而不是选择的值。
It's a combination of 2 functions and they're not playing well together when items are unchecked (ie it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)
我认为如果我使用数组来存储值,在选中/取消选中项目时从数组中添加/删除值会更好,并且我知道如何在 PHP 中而不是在 Javascript 中。这段代码应该创建数组,但我不知道如何将它集成到我的代码中。
$('input:checkbox[name="color[]"]:checked').each(function () {
selectedColors.push($(this).val());
});
现有代码:
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>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/>
</div>Black</a></label>
</li>
<!-- More List Items --!>
</ul>
</div>