Monday 4 February 2013

How to get and set textbox value in jquery with asp.net

In this tutorial , I will explain how to get and set textbox value in jquery.
Firstly , add a latest reference of jquery library file in your page which you can either download from
http://www.jquery.com
or you can add CDN link like :
//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js.

Now, define one textbox control on page like :

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

For getting value of textbox in jquery, simply write :
$('#<textbox ID>').val();

like in above example :
$('#txtName').val();

For setting value of textbox control :
$('#txtName').val('Test');

That's it. Isn't it so simple !!! :-)

But one point I want to mention here that if you are using page in Master page, then it's possible that you will not be able to get and set control value like this because after rendering page, control id gets change like something 'ctl00$MainContent$Pending$txtName'.
So, by using $('#txtName') you will not get or set any thing.
    For getting id of textbox used in master page, you have to change code like :
$('[id$=txtName]').val();
here '$=' is basically used as one of attributes filter and syntax is :
[attribute$=value]
it matches elements that have the specified attribute and it ends with a certain value.



No comments:

Post a Comment