2015-12-18 52 views
2

我对jquery或任何网络技术都很陌生。Jquery - 获取一行的所有内容

这里是我的HTML代码:

<form id = "featureform"> 
     <!-- Table inside the form --> 
     <table id="mytable" class="table table-striped"> 
      <!-- First Row --> 
      <tr id = "tableRow1"> 
       <td><input id="from_checkbox" class="form-input-checkbox" type="checkbox" checked 
              data-toggle="toggle" data-on="From" data-off="From"></td> 
       <td><input type="text" id="from_text" value="[email protected]"></td> 
      </tr> 

      <!-- Second Row --> 
      <tr id = "tableRow2"> 
       <td><input id="to_checkbox" class="form-input-checkbox" type="checkbox" checked 
              data-toggle="toggle" data-on="To" data-off="To"></td> 
       <td><input type="text" id="to_text" value="[email protected]"></td> 
      </tr> 
     </table> 
    </form> 

所以我有一个表单内的表。表中的每一行都有2列。第一列将包含一个bootstrap toggle复选框。文本字段将保存特定复选框的值。两种输入类型(复选框和文本字段)都有与它们关联的ID。

这是我想做的事:这里需要

说明:当用户切换复选框,我想知道的复选框和文本字段的“身份证”。

该表将有多行,因此基于ID的每行硬编码不是解决方案。我要寻找一个通用的解决方案,看起来像这样:

//form-input-checkbox is the class name assigned for every checkbox. So we monitor any events coming from these 
// checkboxes, and do the magic 
$(".form-input-checkbox").change(function(){ 
    // Extract the id of the checkbox 
    // Extract the id of the textfield in this row 
    console.log($(this).closest("tr")); 
}); 

回答

2

您可以使用jQuery attr()方法获取id属性值。要获得对文本字段的引用,首先使用closest()方法获取对外部tr的引用并使用find()方法获取输入字段。

这应该工作。

$(".form-input-checkbox").change(function(){ 
    var _this=$(this); 

    alert(_this.attr("id")); 
    alert(_this.closest("tr").find("input[type='text']").attr("id")); 
}); 

Here是一个工作示例。

+2

谢谢。这是行得通的。欣赏快速反应。 – gixxer

0

这应该可以做到。

$(document).ready(function() { 
     $("input:checkbox[data-toggle='toggle']").change(function() { 
      var $checkbox = $(this); 

      var checkboxId = $checkbox.attr("id"); 
      var inputId = $checkbox.parent().next("td").find("input:text").attr("id"); 

      console.log(checkboxId); 
      console.log(inputId); 
     }); 
    }); 
-1

你的代码应该是这样的:

$(".form-input-checkbox").change(function(){ 
    // Extract the id of the checkbox 
    console.log($(this).attr("id")); 
     // Extract the id of the textfield in this row 
    console.log($(this).closest("tr").find("input[type='text']").attr("id")); 

}); 

这个working plnkr