选中复选框时隐藏表格中的记录

时间:2017-06-29 10:47:14

标签: javascript html

我试图隐藏/显示表格中的记录,具体取决于复选框检查状态

HTML

    <label>Add Additional Once off</label>
    <input type="checkbox" id="chkAdditionalOnceoff" onChange="display();"value="0"><br>
    <label>Add Additional Monthly</label>
    <input type="checkbox" id="chkAdditionalMonthly" onChange="display();"value="0">
    <table>
    <div id="AdditionalOnceoff" style="display:none">
    <tr><td><input type="text" id="txtField1"></td>
        <td><input type="text" id="txtField2"></td>
    </tr>
    </div>
    <tr><td colspan="2">Normal Record to Display always</td></tr>
    <div id="AdditionalMonthly" style="display:none">
    <tr>
        <td><input type="text" id="txtField3"></td>
        <td><input type="text" id="txtField4"></td>
    </tr>
    </div>
    </table>

JAVASCRIPT

function display(){
  if (document.getElementById("chkAdditionalOnceoff").checked) {
   document.getElementById("AdditionalOnceoff").style.display = "inline";
  } else {
   document.getElementById("AdditionalOnceoff").style.display = "none";
  }
   if (document.getElementById("chkAdditionalMonthly").checked) {
   document.getElementById("AdditionalMonthly").style.display = "inline";
  } else {
   document.getElementById("AdditionalMonthly").style.display = "none";
  }
}

因此,当复选框被选中时,相应的&lt; div>包含记录应该隐藏/显示

我找到了这个讨论Hiding other rows in a table when checkbox is selected 但无法找到我的方案的工作示例。

1 个答案:

答案 0 :(得分:0)

希望你能从这里找到解决方案

$(document).ready(function(){
    $('input[type="checkbox"]').click(function(){
        var inputValue = $(this).attr("value");
        $("." + inputValue).toggle();
    });
});
.box{
        color: #fff;
        padding: 20px;
        display: none;
        margin-top: 20px;
    }
    .red{ background: #ff0000; }
    .green{ background: #228B22; }
    .blue{ background: #0000ff; }
    label{ margin-right: 15px; }
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> red</label>
        <label><input type="checkbox" name="colorCheckbox" value="green"> green</label>
        <label><input type="checkbox" name="colorCheckbox" value="blue"> blue</label>
    </div>
    <div class="red box">You have selected <strong>red checkbox</strong> so i am here</div>
    <div class="green box">You have selected <strong>green checkbox</strong> so i am here</div>
    <div class="blue box">You have selected <strong>blue checkbox</strong> so i am here</div>