ASP.net Javascript does not recognize Textarea if it has a runat="server" tag

Asked

Viewed 180 times

1

I have a problem with my Javascript. I am using a server code to do the numbering in a Textarea when the user gives Enter, however, if that TextArea has the tag runat="server" Javascript does not recognize the box and simply doesn’t work.

Javascript Code:

<script type="text/javascript">
            $(document).ready(function () {
                $("#objetivos_projeto").keyup(function (event) {
                    if (event.which != 13)
                        return;
                    var elm = $(this);
                    var lines = elm.val().split("\n");
                    for (var i = 0; i < lines.length; i++)
                        lines[i] = lines[i].replace(/(\d+\.\s|^)/, (i + 1) + ". ");
                    elm.val(lines.join("\n"));
                });
            }); 
        </script>

Textarea code :

<textarea id="objetivos_projeto" runat="server" rows="5" cols="32">1. </textarea> 

However, if you remove the tag runat="server" the Javascript function already recognizes the TextArea and does what he’s supposed to do.

2 answers

1


On Asp.net when you use runat="server" will mean that you will manipulate the component on the server side and not on the client side (browser).

When this occurs, your id who was objetivos_projeto Asp.net will render your id as ex: ctl00$objetivos_projeto.

To prevent Asp.net from changing your id, simply put the parameter ClientIDMode="Static" and then you can keep the runat="server" normally.

Would look this way:

<textarea id="objetivos_projeto" runat="server" ClientIDMode="Static" rows="5" cols="32">1. </textarea> 

1

To solve your problem, put in your javascript event call the following line

project.Clientid

to dynamically grab the ID name.

<script type="text/javascript">
            $(document).ready(function () {
                $('#<%=objetivos_projeto.ClientID%>').keyup(function (event) {
                    if (event.which != 13)
                        return;
                    var elm = $(this);
                    var lines = elm.val().split("\n");
                    for (var i = 0; i < lines.length; i++)
                        lines[i] = lines[i].replace(/(\d+\.\s|^)/, (i + 1) + ". ");
                    elm.val(lines.join("\n"));
                });
            }); 
        </script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.