javascript - jQuery not working for select only one checkbox -


i have built table 4 rows , 8 columns, each checkbox. want 1 checkbox allowed check per row. trying use jquery this. logically, works in jsfiddle not work locally me. did use alert first make sure jquery being loaded first.

here code below. problem is, can still check multiple checkboxes per row when should allowed check one:

 <body>     <h2>checkbox test</h2>     <script type="text/javascript" src="http://localhost/mytesting/jquery-2.1.4.js"></script>     <script type="text/javascript">      function onloadalert() {         alert('sup');     }      $(document).ready(onloadalert);     </script>      <script type="text/javascript">         $('input[type="checkbox"]').on('change', function() {            // uncheck sibling checkboxes (checkboxes on same row)           $(this).siblings().prop('checked', false);            // uncheck checkboxes in same column           $('div').find('input[type="checkbox"]:eq(' + $(this).index() + ')').not(this).prop('checked', false);          });     </script>      <table border="1">      <tbody>     <tr>         <th><b>cost</b></th>         <th colspan="3">reduced cost</th>         <th>neutral</th>         <th colspan="3">increased cost</th>         <th>don't know</th>     </tr>     <tr>         <th></th>         <th>high</th>         <th>medium</th>         <th>low</th>         <th>no effect</th>         <th>low</th>         <th>medium</th>         <th>high</th>         <th></th>     </tr>     <tr>         <td>capital cost</td>         <div>         <td><input type="checkbox" id="matrix1" value="1"></td>         <td><input type="checkbox" id="matrix2" value="1"></td>         <td><input type="checkbox" id="matrix3" value="1"></td>         <td><input type="checkbox" id="matrix4" value="1"></td>         <td><input type="checkbox" id="matrix5" value="1"></td>         <td><input type="checkbox" id="matrix6" value="1"></td>         <td><input type="checkbox" id="matrix7" value="1"></td>         <td><input type="checkbox" id="matrix8" value="1"></td>         </div>      </tr>        </tbody> 

your input elements not siblings, because have different parents – td elements:

<td><input type="checkbox" id="matrix1" value="1"></td> <td><input type="checkbox" id="matrix2" value="1"></td> 

that's why doesn't work:

$(this).siblings().prop('checked', false); 

instead, this:

$(this).closest('tr').find('input').not(this).prop('checked', false); 

fiddle 1


alternatively, use radio buttons having same name:

 <td><input type="radio" name="matrix"></td>  <td><input type="radio" name="matrix"></td>  <td><input type="radio" name="matrix"></td> 

that way, wouldn't need javascript.

fiddle 2


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -