简体   繁体   中英

How can I get the text from an Asp.Net TextBox control with Jquery or Javascript?

I have an Asp.Net TextBox control:

<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom"></asp:TextBox>

In a separate Jquery/Javascript file, I would like get the text from it... normally the text is like '9/1/2015'.

I have tried the following:

var r2FromDate = new Date($(".txtFromDate").val);
var r2FromDate = new Date($(".txtFromDate").val.toString());
var r2FromDate = new Date($(".txtFromDate").val());
var r2FromDate = new Date($(".txtFromDate").text());
var r2FromDate = new Date($(".txtFromDate").text);

and the same with using the # <%= txtFromDate.ClientID %> notation and it completely breaks with that.

Please help!

$('#txtFromDate').val();

您想使用ID而不是类别进行选择。

var text = $("#<%=txtFromDate.ClientId %>").val();

ASP should then output the ID generated on the client and your javascript can select it. You can also reuse this variable instead of querying the DOM over and over [it has to find it every time you use jQuery like "$(...)"].

If your javascript is located in another file, you can use the name attribute instead

<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom" name="txtFromDate"></asp:TextBox>

$('input[name="txtFromDate"]').val();

https://api.jquery.com/attribute-equals-selector/

Alternatively, you can define the following property on your TextBox

ClientIDMode="static"

That will ensure that your ID on the client side will be the same as the server side id.

And then you can use:

$('#txtFromDate').val();

It was actually because I put the id as 'txtFromDate' and the class as 'txtDateFrom' instead of keeping them the same. I was trying to access the class 'txtFromDate' when it didn't exist.

.val() works when you select the right class.

You can try this through this you can also get asp button or any control for that matter.

var txt_txtFromDate = document.querySelector("input[id*='txtFromDate']");
alert(txt_txtFromDate.Value);

you can also try querySelectorAll() if you have multiple controls with same id in client side.

Also, $("input[id*='txtFromDate']") will work.

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