简体   繁体   中英

How do I get the text from a textbox into a variable that is being sent through an AJAX 'POST' request?

I want the text from the 'txtDATE' textbox into the variable press_date. The current AJAX post is working perfectly. (except that it's static and I want the variable). I have been searching for answers and trying everything all day. Any help is appreciated.

<td>
     <asp:TextBox ID="txtDATE" runat="server" AutoPostBack="true" Width="75px" ></asp:TextBox>
</td>
var press = "'1000'";
var press_date = "'2020-08-01'";
$.ajax({
 type: "POST",
 url: "1000TIOT.aspx/GetChartData",
 data: "{ press: " + press +  ", press_date: " + press_date + " }",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (r) {
     var data1 = google.visualization.arrayToDataTable(r.d);
     var chart = new google.visualization.BarChart($("#chart")[0]);
     chart.draw(data1, options);
 },
 failure: function (r) {
     alert(r.d);
 },
 error: function (r) {
     alert(r.d);
 }
});

runat="server" will cause the id to be generated differently to what you would expect so if you add ClientIDMode="Static" the id will be txtDate

<asp:TextBox ID="txtDATE" ClientIDMode="Static" runat="server" AutoPostBack="true" Width="75px" ></asp:TextBox>

you can then pull out the value with

var press_date = $('#txtDATE').val();

Also are you using the autopostback for the date validation or something?

If not and this input is only used in the AJAX call its likely you can just replace this whole input with basic html ie <input type="text" id="txtDate">

you could also use <input type="date" id="txtDate"> to get browser support for a date time picker.

In place of:

   var press_date = "'2020-08-01'";

You should be able to use:

 var press_date = "'" + $('#txtDATE').val() + "'";

I would also consider placing a ClientIDMode="Static" attribute for the text box as this would prevent the server side code from re-naming the txtDATE text box by the server side system. And this will ensure that the jquery selector $('#txtDATE') will be able to reference a un-changed control id. (id = "txtDATE" in this example).

I have it figured out and it works perfectly now.

var press_date = "'" + $('#<%= txtDATE.ClientID %>').val() + "'";

I think I managed to forget, in my frustration, to explain that it was asp code with a vb backend. thank you for the responses and assistance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM