在显示表格时,使用Javascript或jquery向特定列添加复选框

Add checkboxes to a specific column using Javascript or jquery while displaying a table

本文关键字:复选框 添加 jquery 表格 显示 Javascript 使用      更新时间:2023-09-26

我在表中显示这样的数据:

name    country    place      number
ashwin   India      delhi      123
sita     India      Ajmer      456

等等

我想添加复选框悬停到列,并允许用户能够选择该列的多个值。例如,用户可以选择delhiajmer,也可以只选择delhi

请帮助一些jqueryjavascript代码?

试试这个-

HTML -

    <table border="1" id="demo">
<tr>
    <th>name</th>
    <th>country</th>
    <th>place</th>
    <th>number</th>
    <th>check</th>
</tr>
<tr> 
    <td > ashwin </td> 
    <td> India </td>
    <td> delhi </td>
    <td> 123</td>
    <td><input type="checkbox" id="chk1" style="display:none"></td> 
</tr>
<tr> 
    <td > sita </td>
    <td> India </td>
    <td> Ajmer </td>
    <td> 456</td>
    <td> <input type="checkbox" id="chk2" style="display:none"></td>
</tr>
<tr > 
    <td > sita </td>
    <td> India </td>
    <td> Ajmer </td>
    <td> 456</td>
    <td> <input type="checkbox" id="chk2" style="display:none"></td>
</tr>
</table>

JS -

$(document).ready(function(){
        $("#demo tr").mouseover(function() {
               $(this).find("input[type='checkbox']").show();
        });
         $("#demo tr").mouseout(function(){
                var checkbox = $(this).find("input[type='checkbox']");
            if (!checkbox.is(':checked')) {
               $(this).find("input[type='checkbox']").hide();
            }
        });
});

JSFiddle link - https://jsfiddle.net/Lvbj2dmm/10/

    <!DOCTYPE html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("#one").mouseover(function(){
            $("#chk1").show();
        });
        $("#two").mouseover(function(){
            $("#chk2").show();
        });
        $("#one").mouseout(function(){
            if (document.getElementById('chk1').checked) {
           $("#chk1").show();
            }
            else{
            $("#chk1").hide();
        }
        });
        $("#two").mouseout(function(){
            if (document.getElementById('chk2').checked) {
           $("#chk2").show();
            }
            else{
            $("#chk2").hide();
        }
        });

    });
</script>
</head>

<table border="1">
<tr>
    <th>name</th>
    <th>country</th>
    <th>place</th>
    <th>number</th>
    <th>check</th>
</tr>
<tr id="one"> <!--put id as primary number from db -->
    <td > ashwin </td> 
    <td> India </td>
    <td> delhi </td>
    <td> 123</td>
    <td><input type="checkbox" id="chk1" style="display:none"></td> <!--here but use tr id_chk -->
</tr>
<tr id="two"> <!--put id as primary number from db -->
    <td > sita </td>
    <td> India </td>
    <td> Ajmer </td>
    <td> 456</td>
    <td> <input type="checkbox" id="chk2" style="display:none"></td><!--here but use tr id_chk -->
</tr>
</table>
</html>