Dynamically created textboxes and changes plus jQuery in ASP.NET?
I was wondering how to read off a value from a textbox that resides in a partialview and output the value into a textbox within the initial window.
Here's my code...
<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) {
to开发者_StackOverflowtal += 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>
Here's the table where in info is...
<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>
And here's the 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>
This line needs a change in both places:
$("#fieldSummation").text(total);
To this:
$(".fieldSummation").val(total);
To match this:
<input type="text" value="" class="fieldSummation" style="width:120px" />
You need .fieldSummation
with the .
prefix because it's a class, not an ID.
Alternatively, change the input to id="fieldSummation"
instead and leave#fieldSummation
there.
Also, because it's an input, use .val()
to set the value, a normal element uses .text()
, but an input needs .val()
to set it's value=""
attribute.
You can also reduce the overall code here with a function, here's an example with the above problems fixed and DRY coded.
精彩评论