Reputation: 621
I have a table that looks like this:
<table id="start" class="appplytblclr">
<tr class="heading">
<td>First coumn</td>
<td>second column</td>
<td>3rd column</td>
<td>4th column</td>
<tr>
<tr id='1'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='2'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='3'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='4'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='5'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='6'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='7'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
</tr>
</table>
I have a button that, on click, should select the first five check boxes. This is what I've tried so far:
$('#clickbtn').on('click', function (e) {
var sList = "";
$('input[type=checkbox]').each(function () {
sList += $(this).val() + ",";
});
var comma = sList.split(",", 5);
});
but it doesn't seem to work. How should I approach this problem?
Upvotes: 5
Views: 1938
Reputation: 33218
You can use :lt() selector:
$("#selectFirstFive").on("click", function() {
var checkBoxes = $("#start tr td :checkbox:lt(5)");//using :lt get first 5 checkboxes
$(checkBoxes).prop("checked", !checkBoxes.prop("checked"));//change checkbox status based on check/uncheck
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="start" class="appplytblclr">
<tr class="heading">
<td>First coumn</td>
<td>second column</td>
<td>3rd column</td>
<td>4th column</td>
<tr>
<tr id='1'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='2'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='3'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='4'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='5'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='6'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='7'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
</table>
<input type="button" id="selectFirstFive" value="select" />
Upvotes: 5
Reputation: 56439
You can use lt
for this (don't forget about the :checkbox
selector too):
$(":checkbox:lt(5)")
Or if performance is your worry (and you're working with large lists), you can use the much more efficient JavaScript's slice
for this:
$(':checkbox').slice(0, 5)
Upvotes: 4