2010-02-26 27 views
0

我在表中有兩列,並且行是動態創建的。每列讀取值表

<table id ="datatable"> 
    <tr> 
    <td> 
     <input type ="text"> 
    </td> 
    <td> 
     <input type ="text"> 
    </td> 
    </tr> 
</table> 

對於每一行,我想獲取每個表的值並將它們插入到一個對象中,如下所示。

var reading= new Object(); 
reading.Name = (column1).value 
reading.Value = (column2).value 

我該怎麼做?

回答

1
//fetching lines 
$('table tr').each(function(){ 
    var reading = new Object(); 

    reading.name = $(this).find('td:first input').val(); 
    reading.value= $(this).find('td:last input').val(); 

}); 

更新時間:設置錯誤消息,如果是空的

$('table tr').each(function(){ 
    var reading = new Object(); 

    name = $(this).find('td:first'); 
    reading.name = name.find('>input').val(); 
    if(reading.name == '') 
    { 
    name.append('<span>field empty</span>'); 
    } 

    value = $(this).find('td:last'); 
    reading.value = value.find('>input').val(); 
    if(reading.value == '') 
    { 
    value.append('<span>field empty</span>'); 
    } 

}); 
+0

使用上面的代碼,我可以看到它也讀取標題值。我怎樣才能避免讀取標題值? – learning 2010-02-26 10:03:03

+0

標題值是什麼意思?你的意思是標籤或什麼?) – Skay 2010-02-26 10:28:52

+0

是標籤。 只是想問另一個問題: 如果輸入爲空,我想顯示一條錯誤消息。 我可以每次追加一個td到一排我該怎麼做?我試過了,我可以看到列數增加了。或者更好,我如何修改最後一個td以在其中插入標籤? – learning 2010-02-26 10:39:45

0

你可以使用一個選擇器獲取在表格單元格,然後通過他們每個人的使用each function遍歷所有的輸入類型:

// Get the selector. 
var selector = $("#datatable tr td input[type='text']"); 

// Create the object. 
var reading = {}; 

// Cycle through the inputs, attaching the properties. 
selector.each(function (index, element) { 
    // If index is 0, then set the name property. 
    if (index === 0) reading.Name = $(this).val(); 

    // If index is 1, set the value property. 
    if (index === 1) reading.Value = $(this).val(); 
}); 

請注意,選擇器不必如此精確。在這種情況下,也可以使用一個簡單的選擇器,例如#datatabe input(假設所有輸入類型均爲文本字段)。

至於代碼,它嚴重依賴於輸入的位置值,這不是一件好事,因爲佈局可以很容易地改變。相反,您可能想要將輸入類型與名稱或id屬性或自定義數據屬性(前綴爲「data-」,這是一個HTML 5加法,但對4.01 strict有效)進行歸屬,如下所示:

<table id ="datatable">    
    <tr>    
    <td>    
     <input name="Name" type ="text">    
    </td>    
    <td>    
     <input name="Value" type ="text">    
    </td>    
    </tr>    
</table> 

然後,你可以改變你的代碼更加靈活,從屬性值獲取屬性名稱,像這樣:

// Get the selector. 
var selector = $("#datatable tr td input[type='text']"); 

// Create the object. 
var reading = {}; 

// Cycle through the inputs, attaching the properties. 
selector.each(function (index, element) { 
    // Get the selector for the element. 
    var thisSelector = $(this); 

    // Set the value accoding to the name on the element. 
    reading[thisSelector.attr("name")] = thisSelector.val(); 
}); 

這樣,您就可以添加/刪除屬性,而不必更改代碼,因爲它從元素的屬性讀取。

+0

如果我使用<%= Html.textbox()%>,如何設置文本框的名稱? – learning 2010-02-26 07:08:15

+1

@ user281180:ASP.NET MVC中的TextBox擴展方法有一個重載,該對象定義要分配給該元素的屬性。您可以傳遞一個匿名類型,如新的{name =「Value」},它會將「Value」分配給name屬性。另外,我相信還有一個重載,它也接受一個字符串作爲文本框的名字,因爲你通常會在表單元素中使用它。 – casperOne 2010-02-26 09:51:29

+0

使用上面的代碼,我可以看到它也讀取標題值。我怎樣才能避免讀取標題值? – learning 2010-02-26 09:59:30