I’ve got this textbox which I’m trying to access in Javascript/jQuery:
<asp:Textbox ID="txtChosenTime" runat="server"></asp:Textbox>
I’ve tried a handful of variations on:
var TestVal = $("<%=txtChosenTime.ClientID%>");
console.info(TestVal.value);
Also for example:
var TestVal = $("<%=txtChosenTime.ClientID%>").value;
console.info(TestVal);
Or without the $
I’m getting undefined
as the value, if not an error with some of the other variations.
Thank you for any help.
2
Answers
Assuming you have jQuery installed and working?
To select a element by control "id", then you use the format
Note the number "#" or so called pound sign.
and to select by class, you just use
so, in your case?
say like this:
Note that for:
a asp.net text box, you use .val() (to get, or set). Don’t forget the "()"
for a asp.net label, you use .text() (to get or set).
So, I would probably have written the above as:
So, when using jQuery, you use a "method" of that jQuery object, and that getter and setter is thus .val()
As noted, for a label, you use .text().
And, I often since I am somewhat lazy?
I often set the client id = "static", which means for the asp.net processing to NOT change the id of the control.
So, I often do this:
And now my code becomes this:
So, since you "often" has to use that "messy" server side expression to get the correct "id", then I often just as dropping in the text box (or label), add into the markup the clientidmode="static". As a result, then the jQuery code becomes quite a be more clean, and no <%= .ClientID %> expression is required.
Also, note the 2nd code in which I set a value of a label. the VERY cool feature of jQuery is that you can select multiple elements, and then the .val()/.text() will apply to ALL of the elements you match on the page (and wild card selectors are allowed!!).
So, I could have actually written the code this way:
So, I set 3 text boxes in one shot!!!
And as noted, wild cards are allowed, so I could do this:
So, the jQuery selector not limited to "operating" against one control as a result of the jQuery selector.
I see two issues.
#
.value
on a jQuery object, rather than.val()
.Try this:
Alternatively, if this element will not be repeated, you can avoid concerning yourself with server IDs entirely, and add
ClientIdMode="static"
to the element to preserve its assigned ID: