Jquery methods do not run in my view in .net

0

I have these methods in my js:

function soloNumeros(e) {
            var key = window.Event ? e.which : e.keyCode
            return (key >= 48 && key <= 57);
        }

        function soloPegarNumeros(n) {
            permitidos = /[^0-9.]/;
            if (permitidos.test(n.value)) {
                alert("Solo se puede ingresar numeros");
                n.value = "";
                n.focus();
            }
        }

        $("#txtDNI").keypress(soloNumeros(event));

        $("#txtDNI").blur(soloPegarNumeros(this));

And in my view I have this:

<asp:TextBox type="text" autofocus="autofocus" runat="server" ID="txtDNI" MaxLength="8" AutoPostBack="true"/><br />

What I'm doing is validating that you do not write or paste letters in the "txtDni" textbox. But I do not know why he does not get the jquery methods.

    
asked by Gian Franco Alexis Poma Vidal 28.12.2018 в 18:41
source

1 answer

1

Your code has an example of the typical Who is this ? Add the methods in a $(document).ready() and execute them from the same event ( keypress() or blur() ) that triggers them.

$( document ).ready(function() {
  $("#txtDNI").keypress(function(e){
  	 console.log("solo numeros");
  try{
    console.log(e.keyCode);
    var key = window.Event ? e.which : e.keyCode
    return (key >= 48 && key <= 57);
  }
  catch(ex){
  }   
  });
	$("#txtDNI").blur(function(n){
  permitidos = /[^0-9.]/;
  if (permitidos.test(n.value)) {
    alert("Solo se puede ingresar numeros");
    n.value = "";
    $(n).focus();
  }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text"  runat="server" ID="txtDNI" MaxLength="8" AutoPostBack="true"/><br />
    
answered by 29.12.2018 в 01:33