JavaScript function to determine if any checkboxes are checked -
i have table of checkboxes want verify if @ least 1 of checked. wrote little function iterate on checkboxes specific name , check checked property, code never catches scenario no checkboxes checked.
table definition
<div id="testtable"> <table class="table table-striped"> <caption></caption> <thead> <tr> <th>test</th> <th>description</th> </tr> </thead> <tr> <td> <input type="checkbox" id="testa" name="test" title="run testa" /> <label for="testa">testa</label> </td> <td>description of testa</td> </tr> <tr> <td> <input type="checkbox" id="testb" name="test" title="run testb" /> <label for="testb">testb</label> </td> <td>description of testb</td> </tr> </table> </div>
test button
<div class="row"> <div class="form-group"> <span class="input-group-btn"> <button class="btn btn-default" type="button" id="btnruntests">run selected test(s)</button> </span> </div> </div>
script
<script type="text/javascript"> $(document).ready(function () { $('#btnruntests').click(function () { if (!anytestschecked) { $('#divalertmain').html('<div id="divalert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>you must select @ least 1 test run.</div>'); } else { $('#divalertmain').html('<div id="divalert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>good job!</div>'); } window.settimeout(function () { $('#divalert').hide('slow'); }, 10000); }); }); function anytestschecked() { var chk = document.getelementsbyname('test'); var len = chk.length; var foundchecked = false; var = 0; while (i < len && !foundchecked) { if (chk[i].type === 'checkbox' && chk[i].checked) { foundchecked = true; } i++; } return foundchecked; } </script>
you can achieve same thing using below code. (no need write function this)
<script type="text/javascript"> $(document).ready(function () { $('#btnruntests').click(function () { if ($("input[name='test']").prop('checked') == false) { $('#divalertmain').html('<div id="divalert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>you must select @ least 1 test run.</div>'); } else { $('#divalertmain').html('<div id="divalert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>good job!</div>'); } window.settimeout(function () { $('#divalert').hide('slow'); }, 10000); }); }); </script>
Comments
Post a Comment