如何使用Jquery获取选中的复选框行的值?

时间:2017-07-10 12:36:50

标签: javascript jquery html asp.net

我想使用Jquery获取所选复选框行值的值。

为此,首先我尝试提醒消息,如果用户使用Jquery选中了复选框。但我失败了。

  

注意:我使用Jquery连续添加复选框,然后用户将选中该复选框。

以下是我通过AJAX代码添加复选框的代码

$('#btnSearchVendor').click(function(){
    $.ajax({
        type:"POST",
        contentType:"application/json;charset=utf-8",
        url: "GPCreateCheque.aspx/BindData",
        data:"{}",
        dataType:"json",
        success: function (data) {
            alert("success = "+data.d[0].DOCTYPE);
            for(var i=0;i<data.d.length;i++){
                $("#ContentPlaceHolder1_GridView1").append("<tr><td><input id=\"Checkbox"+i+"\" class=\"checkBoxClass\" type=\"checkbox\" /></td><td>" + data.d[i].DOCTYPE + "</td><td>" + data.d[i].DOCNUMBR + "</td><td>" + data.d[i].ActualAmount + "</td></tr>");
            }
        },
        error:function(result){
            alert("Error");
        }
    })
})

用户选择复选框时发出警报的Jquery代码

$('.checkBoxClass').click(function () {
    alert("Checkbox state (method 1) = " + $('.checkBoxClass').prop('checked'));
    //alert("Checkbox state (method 2) = " + $('.checkBoxClass').is(':checked'));
});

以上代码工作正常,我添加了复选框。下面的图片是带控制台的输出 Screenshot of output

2 个答案:

答案 0 :(得分:1)

您可以使用以下脚本

$(document).on('click','.checkBoxClass',function () {
    alert("Checkbox state (method 1) = " +  $(this).prop('checked'));

    if($(this).prop('checked') == true) {
        alert("Actual Amount = " + $(this).closest('tr').find('td:last-child').html());
    }
});

答案 1 :(得分:1)

您可以使用此代码获取所单击复选框的相应行值

$(document).ready(function() {

  $('.checkBoxClass').on('click', function() {
    debugger
    if ($(this).prop('checked')) {
      var columns = $(this).closest('tr').find('td:not(:first-child)');
      $(columns).each(function(index) {
        console.log("Column " + (index + 1) + " has value " + $(this).text());
      });
    }

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1'>
  <thead>
    <tr>
      <th></th>
      <th>Head 2</th>
      <th>Head 3</th>
      <th>Head 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type='checkbox' id='checkbox1' class='checkBoxClass' /></td>
      <td>Content 2</td>
      <td>Content 3</td>
      <td>Content 4</td>
    </tr>
    <tr>
      <td><input type='checkbox' id='checkbox1' class='checkBoxClass' /></td>
      <td>Content 222</td>
      <td>Content 3333</td>
      <td>Content 4444</td>
    </tr>
  </tbody>
</table>

确保仅在选中复选框时才在控制台上打印值。