2010-04-04 69 views
0

我想知道如何從駐留在partialview中的文本框中讀取值,並將該值輸出到初始窗口中的文本框中。在ASP.NET中動態創建文本框和更改以及jQuery?

這裏是我的代碼...

<script type="text/javascript"> 
$(document).ready(function (e) { 

    // Calculate the sum when the document has been loaded. 
    var total = 0; 
    $("#fieldValues :input.fieldKronor").each(function (e) { 
     total += Number($(this).val()); 
    }); 

    // Set the value to the correspondent textbox 
    $("#fieldSummation").text(total); 

    // Re-calculate on change 
    $("#fieldValues :input.fieldKronor").change(function (e) { 
     var total = 0; 
     $("#fieldValues :input.fieldKronor").each(function (e) { 
      total += Number($(this).val()); 
     }); 

     $("#fieldSummation").text(total); 

    }); 
}); </script> 

這裏的表,其中的信息是...

<table id="fieldValues" style="width: 60%; margin-bottom: 2em"> 
      <thead> 
       <tr> 
        <th>Rubrik, t.ex. teknik*</th> 
        <th>Kronor (ange endast siffror)*</th> 
       </tr> 
      </thead> 

      <asp:Panel ID="pnlStaffRows" runat="server"></asp:Panel> 

      <tfoot> 
       <tr> 
        <th></th> 
        <th>Total kostnad</th> 
       </tr> 
       <tr> 
        <td></td> 
        <td><input type="text" value="" class="fieldSummation" style="width:120px" /></td> 
       </tr> 
      </tfoot> 
     </table> 

而這裏的partialview ...

<tr> 
    <td class="greyboxchildsocialsecuritynumberheading4" style="padding-bottom:1em"> 
     <asp:TextBox ID="txtRubrikBox" ToolTip="Rubrik" runat="server" Width="120"></asp:TextBox> 
    </td> 
    <td class="greyboxchildnameheading3" style="padding-bottom:1em"> 
     <asp:TextBox ID="txtKronorBox" class="fieldKronor" ToolTip="Kronor" runat="server" Width="120"></asp:TextBox> 
    </td>    
</tr> 
+0

這是通過你的視圖呈現的局部視圖嗎? – 2010-04-04 15:19:50

+0

你的代碼應該可以正常工作。有問題嗎? – SLaks 2010-04-04 15:20:31

+0

當我運行我的代碼時,沒有發生。 沒有輸入被輸入到名爲fieldSummation的文本框中...... – Grendizer 2010-04-04 18:28:12

回答

0

這條線兩地都需要改變:

$("#fieldSummation").text(total); 

要這樣:

$(".fieldSummation").val(total); 

要匹配這樣的:

<input type="text" value="" class="fieldSummation" style="width:120px" /> 

你需要.fieldSummationwith the . prefix because it's a class,而不是一個ID。
或者,也可以將輸入更改爲id="fieldSummation",並在那裏保留#fieldSummation

此外,因爲它是一個輸入,使用.val()要設置的值,一個正常元件使用.text(),而是一個輸入需要.val()設置它的value=""屬性。

您還可以使用函數here's an example with the above problems fixed and DRY coded來減少整體代碼。

+0

謝謝! 我發現錯誤,該項目沒有正確引用jQuery文件。 再次感謝您的幫助! – Grendizer 2010-04-06 10:54:25