jquery - 如何获得选中的复选框长度
问题描述
试图获得选中的复选框长度,但在它们都被选中时得到 0。
我有一个表,它的行包含 td 的复选框。每个输入类型复选框都有类名“check”。
在表外拥有主复选框,负责选择/取消选择表内的所有复选框。
现在我想看看是否通过单击按钮选中了至少一个复选框。
var allCheckBoxes = $('.check :checkbox:checked');
console.log(allCheckBoxes.length);
它得到的只是零:(
<table id="checkboxTable" class="table table-bordered">
<tbody>
<tr>
<th>Table name</th>
<th>Gen A</th>
<th>Gen B</th>
<th>Actions</th>
</tr>
@foreach($data as $k => $table)
<tr class="trcheck" id="{{$table}}">
<td>{{$table}}</td>
<td><input type="checkbox" name="{{$table}}[]" value="controller" class="check"></td>
<td><input type="checkbox" name="{{$table}}[]" value="model" class="check"></td>
<td>
<button onclick="checkbox_gen_object(this);" id="{{'genbtn'.$i}}" class="genSingle btn btn-primary">
Generate
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
解决方案
function myfunction(){
var mylength=$(".a").filter(':checked').length;
alert(mylength);
$("#leng").val(mylength);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
length: <input type="text" id="leng" name="user"><br>
I have a bike: <input type="checkbox" class="a" name="vehicle" value="Bike"><br>
I have a car: <input type="checkbox" class="a" name="vehicle" value="Car"><br>
I have an airplane: <input type="checkbox" class="a" name="vehicle" value="Airplane"><br>
<input id="btn" onclick="myfunction()" type="button" value="test">