Keypress event does not work after $.get() request

Asked

Viewed 169 times

0

I’m developing a php system and I’m using Jquery for Client Side requests. I have a simple routine for processing inputs that does not allow the user to type a non-numeric character. The script follows:

$('.only-numeric').on('keypress',function(event) {
        var tecla = (window.event) ? event.keyCode : event.which;
        if ((tecla > 47 && tecla < 58 || tecla == 0 || tecla == 44)) return true;
        else {
            if (tecla != 8) return false;
            else return true;
        }
    });

The same is functional, but the problem occurs when I need to work dynamically. I have a select when changing it, update a call div characteristic_item, populating with new inputs through the method $.get(). And with method html() present on screen the new values.

inserir a descrição da imagem aqui

Tela com os campos atualizados

/**
     * Altera as caracteristicas do imóvel pela categoria do imóvel
     */
    $('#id_category').on('change',function (){

        var cat = $(this).val();
        var id = $('#id_immobile').val();
        var url = url_base + '/Imovel/lista_caracteristicas/' + cat + '/' + id;

        $('#characteristic').show();

        $.get(url,function (retorno) {

            if(retorno) {

                $('#characteristic_item').html(retorno);
            } else {
                $('#characteristic').hide();
            }
        });
    });

It turns out that updating DIV values, my script that does not accept non-numeric fields no longer works. I made use of the selector .on(), but I was unsuccessful.

HTML of the project:

 <select class="full-width" data-init-plugin="select2" name="id_category" id="id_category" required>
   <option></option>
</select>

<input type='text' class='form-control only-numeric' name='convenient' id='checkbox' maxlength='3' value=''>                        


Any suggestions on how to solve this case?

  • why, instead of changing the div not only receives new values from select and adds them, so it never changes the select and all events continued to function... for example: $("#id_category option").clear(); retorno.forEach(x=>$("#id_category").append("<option>"+x+"</option>")

  • @balexandre what is changed is not the options of select. select me returns the ID of the category that in turn populates the div that returns the property’s characteristics. I posted the image for ease. See select category feeds the rooms(features) that is in div #characteristic > #characteristic_item

  • I’m sorry, but the way you have the question, I can’t understand the relationship... I believe you see that it’s easy since you’re programming everything, but "on this side" doesn’t give... the code you have in HTML doesn’t have any characteristic or characteristic_item so that we can relate the blocks

  • @balexandre Ok, I’ll rephrase the doubt and include the missing blocks.

  • try creating in Fiddle, Jsbin, Codepen, etc a small example that can reproduce what is failing... you might even find the problem doing so

  • 1

    Just exchange $('.only-numeric').on('keypress',function(event) { for $('body').on('keypress', '.only-numeric', function(event) { that will monitor the keypress even if new elements are included with the class only-numeric on the page dynamically.

  • @Benilson perfect, now I understood the behavior. I thought just using the on() in the keypress event it would already be included to the DOM dynamically. Problem solved and understood. :)

  • 1

    Hello, we do have problems with Ajax requests that add elements to the DOM. A palliative way to solve your problem would be to reload the screen as a whole. Thus the events for the new elements would be recorded. What you could do is to add an onchange event to that class and not allow the user to put non-numeric characters. I don’t know where you stand in the development of this application, but I strongly recommend you use some library like Angular React or Vuejs.

  • 1

    @Benilson add a reply with your solution, so the author can choose it and improve it

Show 4 more comments

1 answer

1

You are creating new fields on the screen, but your javascript has already been loaded and it will not identify the new elements. Since I don’t know how your file is, follow what you can do.

Suggestion 1: Place code directly in the input being created: <input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57">

Suggestion 2: 1. Bundle your "allow only numeric" script into a function.


function minhaFuncao(){
   $('.only-numeric').on('keypress',function(event) {
        var tecla = (window.event) ? event.keyCode : event.which;
        if ((tecla > 47 && tecla < 58 || tecla == 0 || tecla == 44)) return true;
        else {
            if (tecla != 8) return false;
            else return true;
        }
    });
}

  1. Call this script every time you refresh the screen:
//....código pra cima
if(retorno) {

                $('#characteristic_item').html(retorno);

                //Aqui vai a função
                minhaFuncao();

            } else {
                $('#characteristic').hide();
            }
//....código pra baixo
  • Thanks for the answer. I had already done it that way, but I was dissatisfied because I knew I had a better way to do it. Thanks anyway. The @Benilson response clarified and solved my problem.

Browser other questions tagged

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