Remember to insert jQuery into the page and run the script only after you've loaded HTML. Because the code itself works perfectly - see the executable example at the end of the answer.
You said in the question that you are using ASP.NET, then the problem should be with the order of things. Note that script is adding a listener to the keyup event of an element on your page, and for this to work properly, this listener is bound after the HTML element has been created . Because it makes no sense to add an event to a non-existent element, right?
Almost always, in ASP.NET, scripts are defined within a section at the bottom of the page, but these scripts are usually "rendered" by view before HTML - this is set on the "master" page of the layout
An interesting way to get around this unwanted effect is to put the code inside $(document).ready()
, to make sure that the attempt to register the event will only be made after the element has already been created. Something like:
$(document).ready(function() {
$("#num").keyup(function (event) {
// Seu código
});
});
Another possible problem, also related to the "order of things", is whether the element was created dynamically via JavaScript.
In this case, it is necessary to "listen" for an event in body , with target (target) element. For example:
$('body').on('keyup', '#num', function (event) {
// Seu código
});
Executable example of your code:
$("#num").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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="num" rows="5" cols="32">1. </textarea>