1

I'm trying to change the value of an asp:textbox using jQuery using this line of code that I've found referenced in several places:

$("#<%= element.ClientID %>").attr('value', "");

However, I keep getting a syntax error saying that the first part is an invalid expression. I'm sure it's something simple I'm missing here, just don't know what it is.

jQuery is linked via the master page and the .js file with the function containing the line in question is individually linked on the specific page.

0

5 Answers 5

1

Your syntax is correct:

$('#<%= textbox.ClientID%>').val('new textbox value');

is the correct syntax for selecting an <asp:textbox /> via javascript and in this case jQuery; however, this only works in .ASPX files.

You will need to convert this separate .js file to an in-line script in your .ASPX page for this to work.

Alternatively, you could use a CSS class as a selector, which will work from your external .js file:

In your .JS file

$('.uniqueCSSClassName').val('new textbox value');

In your .ASPX file

<asp:textbox ID="whatever" CssClass="uniqueCSSClassName" />

This will allow you to select your text box from an external javascript file. This is not a pretty approach, but it will work. I would go for the first option, and move my .js code into an inline script.

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

Comments

1
<script runat="server" type="text/javascript">
    $("#<%= element.ClientID %>").val("");
</script>

Comments

0

Is this code in an .aspx page, or in a .js file? The asp engine doesn't process javascript files, so it wouldn't turn <%= element.ClientID %> into the actual client id.

Also, the line of code to set the value of the textbox should be:

$('selector').val('');

If you want to keep your javascript separate, use a class instead.

3 Comments

Since his .js is in a separate file, OP can use classes to target elements.
The code is in the .js file. Guess that's the error then. Is it possible to reference the asp:element from a .js file?
I'll try using a class as suggested
0

you need to define your element's ID in the place of 'element', like:

$("#<%= yourElementId.ClientID %>").attr('value', "");

and that element should have runat="server" attribute

Comments

0

try this.

$('[id$=textboxID]').val();

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.