0

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!

1
  • You're using a class selector but you're specifying an ID. Try with $(".txtDateFrom").val() Commented Sep 18, 2015 at 20:54

5 Answers 5

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

You want to select using the ID, not the class.

Sign up to request clarification or add additional context in comments.

1 Comment

Just because the ID is txtFromDate on the server-side, there's no guarantee that it will be that on the rendered HTML (unless you said the ClientIDMode property to static). The answer above does it correctly by acquiring the ClientID and then using that.
1
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/

Comments

0

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();

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.