我正在实现 html 多选选项复选框元素。我从 fiddle 中找到了以下代码片段。( https://jsfiddle.net/KyleMit/mqcp7f3s/413/ )。 我想添加一个 selectAll 复选框来一次选择所有复选框。而且我想获取选定的复选框值。但选择所有功能不起作用
HTML:
<h3>Font Awesome</h3>
<select id="animals" multiple="" class="form-control select-checkbox-fa" size="5">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</select>
<button id="selectall">Click</button>
</button>
CSS:
body {
padding: 15px;
}
.select-checkbox option::before {
content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
}
.select-checkbox option:checked::before {
content: "\2611";
}
.select-checkbox-fa option::before {
font-family: FontAwesome;
content: "\f096";
width: 1.3em;
display: inline-block;
margin-left: 2px;
}
.select-checkbox-fa option:checked::before {
content: "\f046";
}
Jquery:
$('option').mousedown(function(e) {
e.preventDefault();
var originalScrollTop = $(this).parent().scrollTop();
console.log(originalScrollTop);
$(this).prop('selected', $(this).prop('selected') ? false : true);
var self = this;
$(this).parent().focus();
setTimeout(function() {
$(self).parent().scrollTop(originalScrollTop);
}, 0);
return false;
});
$('#selectall').click( function() {
$('#animals').each(function() {
var checkboxes = $(this).find("option:checked");
checkboxes.each(function() {
$(this).prop('selected', true);
});
});
});
最佳答案
请检查一下
$('#selectall').click(function () {
$('#animals option').prop('selected', true);
});
$('#getValues').click(function () {
console.log("JHGHJ", $('#animals :selected').text());
});
body {
padding: 15px;
}
.select-checkbox option::before {
content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
}
.select-checkbox option:checked::before {
content: "\2611";
}
.select-checkbox-fa option::before {
font-family: FontAwesome;
content: "\f096";
width: 1.3em;
display: inline-block;
margin-left: 2px;
}
.select-checkbox-fa option:checked::before {
content: "\f046";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Font Awesome</h3>
<select id="animals" multiple="" class="form-control select-checkbox-fa" size="5">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</select>
<button id="selectall">select All </button>
<button id="getValues">get Values</button>
</button>
关于javascript - 如何实现html多选选项复选框的全选功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61402597/