![](/img/trans.png)
[英]Looping into a Table and getting values from different Inputs inside the Columns
[英]Split values from table into different text inputs?
我有一個由用戶輸入填充的表。 例如,First Name和Last Name有一個文本輸入。 John在一個輸入中,而Smith在下一個輸入中,將在Name列下添加表作為John Smith,一個包含2個值的字符串。 這是正常工作,以及地址列...但是從表到輸入的值是問題。 單擊相應的行會填充輸入,但我需要拆分這些值以填充正確的輸入(以便將John Smith再次拆分為名字和姓氏)。 有任何想法嗎? 提前致謝。
jQuery的
/* Add a click handler to the rows - this could be used as a callback */
$("#example tbody tr").click(function (e) {
if ($(this).hasClass('rowSelected')) {
$(this).removeClass('rowSelected');
} else {
oTable.$('tr.rowSelected').removeClass('rowSelected');
$(this).addClass('rowSelected');
}
var properties; // all td from .row_selected
properties = fnGetSelected(oTable).find("td");
$("#fName").val(properties.eq(0).text());
$("#email").val(properties.eq(1).text());
$("#company").val(properties.eq(2).text());
});
我建議您使用相應的類名將數據行元素包裝在span中。 給出名字和姓氏的例子,
JS
$('#addRow').click(function () {
var row =$('#example').dataTable().fnAddData([
'<span class="fname">'+$("#fName").val()+'</span> <span class="lname">' + $("#lName").val()+'</span>',
$("#email").val(),
小提琴的html
<td><span class='fname'>John</span> <span class='lname'>Smith</span></td>
然后它是直接和清晰的,以獨立於其文本格式檢索值。
在小提琴中,您還可以找到用於將點擊功能邏輯與新添加的行相關聯的代碼,以便可以選擇它們。
$('#addRow').click(function () {
var row =$('#example').dataTable().fnAddData([
'<span class="fname">'+$("#fName").val()+'</span> <span class="lname">' + $("#lName").val()+'</span>',
$("#email").val(),
$("#company").val() + '<br>' + $('#address').val()]);
$(oTable.fnGetNodes(row)).click( function( e ) {
if ($(this).hasClass('rowSelected')) {
$(this).removeClass('rowSelected');
} else {
oTable.$('tr.rowSelected').removeClass('rowSelected');
$(this).addClass('rowSelected');
}
var properties; // all td from .row_selected
properties = fnGetSelected(oTable).find("td");
$("#fName").val(properties.eq(0).find('.fname').text());
$("#lName").val(properties.eq(0).find('.lname').text());
$("#email").val(properties.eq(1).text());
$("#company").val(properties.eq(2).text());
});
為了保持代碼DRY,最好將click函數邏輯放在函數中並直接調用它,而不是復制代碼。
如果您100%確定姓氏和名字是由空格分隔的,則可以使用以下代碼:
$("#fName").val(properties.eq(0).text().split(' ')[0]);
$("#lName").val(properties.eq(0).text().split(' ')[1]);
地址:
$("#company").val(properties.eq(2).html().split('<br>')[0].trim());
$("#address").val(properties.eq(2).html().split('<br>').splice(1).join('\n').trim());
小提琴: http : //jsfiddle.net/Z85QC/11/
你可以做一個簡單的改變,如:
var properties; // all td from .row_selected
properties = fnGetSelected(oTable).find("td");
var names = properties.eq(0).text().split(' ');
$("#fName").val(names[0]);
$("#lName").val(names[1]);
$("#email").val(properties.eq(1).text());
$("#company").val(properties.eq(2).text());
但是,只有當你確定First和Last名稱由一個恆定的單個空格分隔時,否則你必須更改一點......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.