2014-09-03 147 views
0

我有两列表有多行。此外,我还有一些隐藏字段来填充列中的值。现在我想在点击某个按钮时将隐藏字段的值加载到表格的列中。用jquery动态添加列内容

<table> 
    <tbody> 
    <tr> 
     <th>ACL</th> 
     <td></td> 
     <input id="field0" type="hidden" value="Access Control List"/> 
    </tr> 
    <tr> 
     <th>Bcc</th> 
     <td></td> 
     <input id="field1" type="hidden" value="Blind Carbon Copy"/> 
    </tr> 
    ...... 
    </tbody> 
</table> 

什么简单的方法来实现这个?

+2

告诉我们你到目前为止尝试过什么。 – 2014-09-03 21:38:37

回答

0

如果你给你的表中的ID,并希望所有的输入移动到相邻的TD的:

$("#<your_button_id>").click(function() { 
    $("#<your_table_id> td").each(function() { 
     $(this).html($(this).siblings("input").val()); 
    }); 
}); 
+0

这是不是更多依赖于“输入”框中的HTML位置?如果我们将隐藏的文本框移动到页面的不同部分,会发生什么? – anjibcs 2014-09-03 21:50:07

+0

是的,它假定输入框是td的兄弟,就像它们在您的示例中一样。如果你想把它们移到其他地方,你可以通过id $(“#id”)或class $(“。class”)来定位它们。 – 2014-09-03 21:55:22

+0

你是否按照你想要的方式工作? – 2014-09-03 22:01:37

0

你不需要保存在文本框中的值可以保存在HTML属性前值:data-value

尝试这种方式

<table> 
    <tbody> 
    <tr> 
     <th>ACL</th> 
     <td data-value="Access Control List"> 
      <button class="show-value">Show Value</button>    
     </td> 
    </tr> 
    <tr> 
     <th>Bcc</th> 
     <td data-value="Blind Carbon Copy"> 
      <button class="show-value">Show Value</button> 
     </td> 
    </tr> 
    </tbody> 
</table> 

JAVASCRIPT

$(document).ready(function(){ 
    $(".show-value").click(function(){ 
    var theValue = $(this).parent('td').attr('data-value'); 
    $(this).parent('td').html(theValue); 
    }); 
}); 
0

如果您的意思是td元素旁边的input,则解决方法是这样的。我使用next()来引用下一个,但如果它是相同的级别但可以在之前,则可以使用siblings

如果输入处于较低级别,则还可以使用parent()find()遍历DOM。

见工作样本:http://jsfiddle.net/3qw09a0p/

$(document).ready(function(){ 
    $("#mybutton").click(function() { 
     $("#mytable td").each(function() { 
      $(this).html($(this).next("input").val()); 
     }); 
    }); 
}); 

使用文档准备方法,以确保您的内容已加载。

0

虽然已经足够了答案对于这一点,我想补充我的方法:

$("input[type='button']").click(function() 
{ 
    $("input[type='hidden']").each(function() 
    { 
    $(this).parents("tr").find("td").text($(this).val()); 
    });  
}); 

没有ID需要,就像<input type="button" value="Click"/>一个按钮。
它也适用于您在问题中提供的表格,其中输入未包含在列中,我建议您使用有效的HTML。猜你刚刚忘了,因为你提到你会有一个2列表;)