我正在尝试使用复选框值填充两个文本字段。它将从复选框中获取最小和最大数据属性值,找到最大和最小数字,并使用该值设置输入字段。如果未选中所有复选框,则将设置默认值。
例如,如果选中 50-100 和 200-300 选项,则最小输入将设置为 50,最大输入字段将设置为 300
var lowest = +Infinity;
var highest = -Infinity;
$("input[type='checkbox']").on('click', function () {
if ($(this).filter(':checked').length > 0) {
lowest = Math.min(lowest, parseFloat($(this).attr("data-min")));
highest = Math.max(highest, parseFloat($(this).attr("data-max")));
$("#price-min").val(lowest);
$("#price-max").val(highest);
} else {
$("#price-min").val(1);
$("#price-max").val(150000);
}
});
这是我的 html :
<input id="price-min" type="text" value="0">
<input id="price-max" type="text" value="0"><br><br>
<input type="checkbox" data-min="50" data-max="100">50-100<br>
<input type="checkbox" data-min="100" data-max="200">100-200<br>
<input type="checkbox" data-min="200" data-max="300">200-300
最佳答案
在:checkbox
的变更事件中全部勾选min
和max
使用 map()
获取两个数组中的值方法,然后使用 sort()
对这两个数组进行排序.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="price-min" type="text" value="0">
<input id="price-max" type="text" value="0">
<br>
<br>
<input type="checkbox" data-min="50" data-max="100">50-100
<br>
<input type="checkbox" data-min="100" data-max="200">100-200
<br>
<input type="checkbox" data-min="200" data-max="300">200-300
<script>
$("input[type='checkbox']").change(function () {
var min = $('input:checkbox:checked').map(function () { return $(this).data('min') }).get().sort(function (a, b) { return a - b });
var max = $('input:checkbox:checked').map(function () { return $(this).data('max') }).get().sort(function (a, b) { return b - a });
if (min.length) {
$("#price-min").val(min[0]);
$("#price-max").val(max[0]);
} else {
$("#price-min").val(1);
$("#price-max").val(150000);
}
});
</script>
关于javascript - 使用复选框填充输入字段 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673292/