Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a textbox value by JQuery

Tags:

jquery

asp.net

I am setting a TextBox controls value via an ajax post.

$('#txtSite').val(msg.d.SiteName);

This is working and the value of the TextBox is altered correctly. But, when I come to posting the information to the database, the txtSite.Text value is empty!!

Any ideas? Am I going mad?

Code to populate the TextBox:

$.ajax({
    type:"POST",
    url: "MyPage.aspx/ValidateSite",
    data: "{ siteID: '" + $('#txtSiteID').val() + "' }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        if (msg.d != null) {
            $('#txtSite').val(msg.d.SiteName);  // It's definitely doing this
        }
        else {
            $('#txtSite').val('');
        }
    },
    error: function(msg) {
    }
});

Code to save to the server (all connectivity etc. is correct and working). This code is in an ASP button click event:

SqlCommand cmd = new SqlCommand("INSERT INTO [Sites] ([SiteName]) VALUES ('" + txtSite.Text + "')", conn);
cmd.ExecuteNonQuery();

The TextBox is defined like so:

<asp:TextBox ID="txtSite" runat="server" AutoComplete="off" TabIndex="4" MaxLength="50" Style="width: 230px" Enabled="false" CssClass="FormDisabledTextWithSmallHeight" />

I have also tried changing my JQuery to use plain Javascript instead and doing this:

document.getElementById("txtSite").value = msg.d.SiteName;

Still returns me an empty value.

like image 817
Neil Knight Avatar asked Jan 23 '13 16:01

Neil Knight


1 Answers

You have your textbox set to Enabled="false" which renders in the browser with a disabled="disabled". Disabled form inputs are not submitted.

The solution is either to make the textbox enabled and read-only:

txtSite.Enabled = true;
txtSite.Attributes.Add("readonly", "readonly"); //on prerender event or somewhere else

or to use a different element set with runat="server", like a <asp:HiddenField /> and update both the textbox and the alternate element with your AJAX call:

success: function(msg) {
    if (msg.d != null) {
        $('#txtSite').val(msg.d.SiteName);
        $('#hiddenInput').val(msg.d.SiteName);
    } else {
            $('#txtSite').val('');
    }
}
like image 62
pete Avatar answered Oct 14 '22 07:10

pete