Select the first 5 checkbox from the table by clicking on the button
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, when clicked, should select the first five checkboxes. This is what I have 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 does not seem to work. How do I approach this problem?
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" />