ASP.net JavaScript does not recognize the TextArea if it has a Tag runat="server"

1

I have a problem with my JavaScript. I am using a code that server 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 does not 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 runat="server" tag the JavaScript function already recognizes TextArea and does what it is supposed to do.

    
asked by anonymous 21.06.2017 / 16:51

2 answers

1

In ASP.NET when you use runat="server" it will mean that you will handle the component on the server side and not on the client side.

When this happens, your id that was objetivos_projeto asp.net will render your id like ex: ctl00$objetivos_projeto .

To prevent ASP.NET from changing its id, you just have to set the ClientIDMode="Static" parameter and then you can keep runat="server" normally.

It would look like this:

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

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

  

project_projects.ClientID

to get the name of the ID dynamically.

<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>
    
21.06.2017 / 17:02