I am facing a weird issue and not sure whether it's jquery or combination of my scenario that is causing this. When I set the textbox value using jquery, the textbox displays correct value but the value attribute inside the html is still the one that it was loaded with. Why is it displaying different text then the one in the DOM?
I am having a dynamically generated form which adds two number and displays the addition into third textbox using jquery as shown below. You can reproduce using below code
The designer file
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".addToTotal").blur(function () {
UpdateTotal();
});
});
function UpdateTotal() {
var add = 0;
$(".addToTotal").each(function () {
add += Number($(this).val());
});
$(".txtTotalPoints").val(add.toFixed(2));
$("#para").text("Sum of all textboxes is : " + add);
}
</script>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<input id="addAll" type="button" value="Sum all Textboxes" /><br />
<p id="para"> </p>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Code behind file that dynamically adds control is
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt1 = new TextBox();
txt1.ID = "txt1";
txt1.CssClass = "addToTotal";
TextBox txt2 = new TextBox();
txt2.ID = "txt2";
txt2.CssClass = "addToTotal";
TextBox txt3 = new TextBox();
txt3.ID = "txt3";
txt3.CssClass = "txtTotalPoints";
PlaceHolder1.Controls.Add(txt1);
PlaceHolder1.Controls.Add(txt2);
PlaceHolder1.Controls.Add(txt3);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UpdateTextBoxTextProperty(this);
}
}
private void UpdateTextBoxTextProperty(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c is TextBox)
{
string Id = c.ID;
string fieldName = Id.Substring(3);
(c as TextBox).Text = fieldName;
}
if (c.Controls.Count > 0)
{
UpdateTextBoxTextProperty(c);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}