2014-10-28 32 views
2

如果选中了同一行复选框,我希望获得整行的值。例如如果在jquery中单击该行的复选框,如何获取行的值

<table id="tbl" border="1"> 
    <tr><input type="checkbox" id="selectall"/> 
     <td> 
     <input type="checkbox"/></td> 
<td>2</td> 
<td>3</td> 
<td>4</td> 
    </tr> 
    <tr><td><input type="checkbox"/></td> 
<td>2</td> 
<td>3</td> 
<td>4</td> 
    </tr> 
    <tr><td><input type="checkbox"/></td> 
<td>2</td> 
<td>3</td> 
<td>5</td> 
    </tr> 
</table> 
<input type="button" value="save"/> 

$('#selectall').click(function(event) { 
      if(this.checked) { 
       // Iterate each checkbox 
       $(':checkbox').each(function() { 
        this.checked = true; 
       }); 
      } 
      else { 
      $(':checkbox').each(function() { 
        this.checked = false; 
       }); 
      } 

     }); 

$("#save").click(function(){ 
    /If all selected value has to pass through ajax one by one row/ 
}); 

如果我按下保存按钮,我必须选择所有有效的行值。请参考fiddle。请帮帮我 。在此先感谢

+0

什么期望的数据格式 – 2014-10-28 06:50:25

+0

DATAFORMAT应阵列。这样,如果选中,我可以获得['1','2','3']的价值。或任何其他格式,应该很容易解析,如果我通过ajax – 2014-10-28 06:54:23

回答

4

尝试

$('#selectall').click(function(event) { 
 
    $(':checkbox').prop('checked', this.checked); 
 
}); 
 

 
$("#save").click(function() { 
 
    //reset the logger 
 
    $('#log').empty(); 
 

 
    //get all the checked checboxex 
 
    $('#tbl input:checkbox:checked').each(function() { 
 
    //for each checked checkbox, iterate through its parent's siblings 
 
    var array = $(this).parent().siblings().map(function() { 
 
     return $(this).text().trim(); 
 
    }).get(); 
 
    //to print the value of array 
 
    $('#log').append(JSON.stringify(array)) 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="checkbox" id="selectall" /> 
 
<table id="tbl" border="1"> 
 
    <tr> 
 
    <td> 
 
     <input type="checkbox" /> 
 
    </td> 
 
    <td>2</td> 
 
    <td>3</td> 
 
    <td>4</td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="checkbox" /> 
 
    </td> 
 
    <td>2</td> 
 
    <td>3</td> 
 
    <td>4</td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="checkbox" /> 
 
    </td> 
 
    <td>2</td> 
 
    <td>3</td> 
 
    <td>5</td> 
 
    </tr> 
 
</table> 
 
<input type="button" id="save" value="save" /> 
 
<div id="log"></div>

+0

其工作非常感谢 – 2014-10-29 11:54:16

+0

嗨,兄弟。你能告诉我现在把它改成json格式吗? – 2014-11-02 18:24:04

0

可以得到选中的复选框,并使用.closest()让自己最亲近的行元素对象:

$('input:checked').closest('tr'); 

如果你正在寻找前页获得相对于选中的复选框的TD元素,那么你可以使用:

$('input:checked').parent().siblings(); //if checkbox 3 is checked then it will have 3rd rows other three td elements having text 2,3,5. 

更新:,让他们在阵列

arr=[]; 
/If all selected value has to pass through ajax one by one row/ 
$('input:checked').parent().each(function(){ 
    arr.push($(this).siblings().map(function(){ 
    return $(this).text() 
    }).get()); 
}); 
console.log(arr); 

Working Demo

相关问题