Skip to content
29/06/2010 / Danresa Consultoria de Informática

ReadOnly ASP.NET TextBox at RunTime using jQuery

n this short and simple article, we will see how to check a condition and make a TextBox readonly at runtime using jQuery.
This article is a chapter from my EBook called 51 Recipes with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an article.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. The code shown below has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.
Let us quickly jump to the solution to check if the TextBox has some value in it and make it read-only.
<head id=”Head1″ runat=”server”>
    <title>Make TextBoxes ReadOnly at RunTime</title>
   
    <script type=”text/javascript”
    </script>      
   
    <script type=”text/javascript”>
        $(function ()
        {
            $(‘input:text[value!=]’).each(function ()
            {
                $(this).attr(‘readonly’, true);
            });
        });
    </script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div class=”bigDiv”>
        <h2>Make TextBoxes ReadOnly at RunTime</h2><br />
        <asp:TextBox ID=”tb1″ runat=”server” Text=”ReadOnlyText”/><br />
        <asp:TextBox ID=”tb2″ runat=”server” Text=””/><br />
        <asp:TextBox ID=”tb3″ runat=”server” Text=””/><br />
        <asp:TextBox ID=”tb4″ runat=”server” Text=”ReadOnlyText” />
        <br /><br />
        Tip: 1st and 4th TextBoxes have been made read-only
        and cannot be edited
    </div>
    </form>
</body>
</html>
 
This is a very common requirement that most developers face on a daily basis. While editing a form, textboxes that have text in it, should be made read-only. The code shown in the example filters the textboxes that have values in it (tb1 and tb4) and applies the ‘readonly’ attribute to them.
$(‘input:text[value!=]’).each(function() {
     $(this).attr(‘readonly’, true);
});
When the document loads, the user is able to enter text in the second and third textboxes, but not in the first and fourth, since they are now read-only. It is that simple!
TextBox
Anúncios

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

%d blogueiros gostam disto: