2015-04-03 16 views
0

我在html表上創建動態行並嘗試在c#上獲取表值。但每當我把runat=server放在表jQuery不起作用,因此我無法訪問服務器端的html表。請給我一些建議。如何在服務器端c#上訪問html表而不使用runat = server

<table id="purchaseItems" name="purchaseItems" align="center"> 
    <tr> 
     <th>Paragraph</th> 
     <td> 
      <input type="text" name="description[]" class="tbDescription next" required /> 
     </td>        
     <td> 
      <input type="button" name="addRow[]" class="add" value='+' /> 
     </td> 
     <td> 
      <input type="button" name="addRow[]" class="removeRow" value='-' /> 
     </td> 
    </tr> 
</table> 

,這是我的jQuery:

$(document).ready(function() { 

$(document).on('click', '#purchaseItems .add', function() { 

    var row = $(this).closest('tr'); 
    var clone = row.clone(); 

    // clear the values 
    var tr = clone.closest('tr'); 
    tr.find('input[type=text]').val(''); 

    $(this).closest('tr').after(clone); 

}); 

$(document).on('keypress', '#purchaseItems .next', function (e) { 
    if (e.which == 13) { 
     var v = $(this).index('input:text'); 
     var n = v + 1; 
     $('input:text').eq(n).focus(); 
     //$(this).next().focus(); 
    } 
}); 

$(document).on('keypress', '#purchaseItems .nextRow', function (e) { 
    if (e.which == 13) { 
     $(this).closest('tr').find('.add').trigger('click'); 
     $(this).closest('tr').next().find('input:first').focus(); 
    } 
}); 
$(document).on('click', '#purchaseItems .removeRow', function() { 
    if ($('#purchaseItems .add').length > 1) { 
     $(this).closest('tr').remove(); 
    } 
}); 

});

+0

把'runat = server'放在你的表中,而不是'#purchaseItems',使用'#<%= purchaseItems.ClientID%>'來訪問jquery中的表。 – Prashant16 2015-04-03 06:44:26

回答

1

你的問題是由asp.net生成的ID。加入runat =「server」後,它不會是簡單的purchaseItems。要獲得真實ID,您應該使用下一個代碼:

$(document).on('keypress', '#<%= purchaseItems.ClientID %> .next', function (e) { 
    if (e.which == 13) { 
     var v = $(this).index('input:text'); 
     var n = v + 1; 
     $('input:text').eq(n).focus(); 
     //$(this).next().focus(); 
    } 
}); 

但是在這種情況下,您將無法分離js和asp.net文件。作爲替代解決方案,您可以從任何瀏覽器使用開發工具,找出客戶端將生成的ID。

+3

或者簡單地將'ClientIDMode =「Static」' - 服務器和客戶端ID將由用戶設置相同。 – 2015-04-03 06:46:20

相關問題