I want to display selections count in textbox from dropdown checkboxes, how this can be done?
$(':checkbox').change(function() {
$("input[type='text'"]).val("All fruits")
});
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL jjXkk Q2h455rYXK/7HAuoJl 0I4" crossorigin="anonymous"></script>
<div >
<input type="text" data-bs-toggle="dropdown" value="2 Fruits selected" aria-expanded="false" data-bs-auto-close="outside" readonly>
<div >
<div >
<label >
<input type="checkbox" value=""> Fruit1 </label>
<label >
<input type="checkbox" value=""> Fruit2 </label>
<label >
<input type="checkbox" value=""> Fruit3 </label>
<label >
<input type="checkbox" value=""> Fruit4 </label>
</div>
</div>
</div>
</body>
</html>
CodePudding user response:
In the change
listener, get the number of checked checkboxes by using the checked
pseudo-class. Then, just compare the length of the selected elements list:
const totalLength = $('input[type="checkbox"]').length
$(':checkbox').change(function() {
const checked = $('input[type="checkbox"]:checked').length
$("input[type='text']").val(checked == totalLength ? "All fruits" : `${checked} Fruits selected`)
});
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL jjXkk Q2h455rYXK/7HAuoJl 0I4" crossorigin="anonymous"></script>
<div >
<input type="text" data-bs-toggle="dropdown" value="2 Fruits selected" aria-expanded="false" data-bs-auto-close="outside" readonly>
<div >
<div >
<label >
<input type="checkbox" value=""> Fruit1 </label>
<label >
<input type="checkbox" value=""> Fruit2 </label>
<label >
<input type="checkbox" value=""> Fruit3 </label>
<label >
<input type="checkbox" value=""> Fruit4 </label>
</div>
</div>
</div>
</body>
</html>