function js calling twice

Asked

Viewed 515 times

0

I am having a problem creating a function in java script that needs to be executed in a file but this calling several times the same function when I try to put the function in input does not work follow the code:

<form class="myform"  onkeydown="ProdUpCad()">
    <input type="hidden"  name="id" value="<?php echo $prod->id_prduto ?>">

     // esta h1 se transforma em input   
     <h1 class="card_prod__title text-white editable-area"><?php echo $prod->nome_prod?></h1>

</form>

my func.js

function ProdUpCad() {
 $("form.myform").on("focusout", function(e) {
        var form = $(this);
        var url = form.attr('action');
        e.preventDefault(); 
        $.ajax({
            type: "POST",
            url: "update/update_prod_name.php",
            data: form.serialize(),
            success: function(data) {
            }
        });
    });
    }

1 answer

1


It is calling twice because you have registered multiple events in your function.

The way you did, you’re calling the event onkeydown, that when calling its function, records the event of focusout, so he’s calling multiple times, one by pressing a key (onkeydown) and the other when losing focus (focusout).

Ideally you register the event focusout only once, and remove the event onkeydown, that in this case he would several times call his POST when a key is pressed.

Your code would look like this, removing the event onkeyup:

<form class="myform">
    <input type="hidden"  name="id" value="<?php echo $prod->id_prduto ?>">

     // esta h1 se transforma em input   
     <h1 class="card_prod__title text-white editable-area"><?php echo $prod->nome_prod?></h1>    
</form>

Now register the event of focusout page loading, only once:

 $("form.myform").on("focusout", function(e) {
        var form = $(this);
        var url = form.attr('action');
        e.preventDefault(); 
        $.ajax({
            type: "POST",
            url: "update/update_prod_name.php",
            data: form.serialize(),
            success: function(data) {
            }
        });
    });

See also: Differences between Onkeyup, Onkeydown and Onkeypress?

  • the problem is that when I do it doesn’t work anymore

  • Place the focusout function on the loading of your page, inside the script tag. It is important that it is not inside any function. Also try inside the Document ready (https://learn.jquery.com/using-jquery-core/document-ready/)

  • it worked you could help me with one more question?

  • Of course, please create a new question =)

  • I created this la ja

  • https://answall.com/questions/433698/como-especificar-o-campo-input-clonado-js

Show 1 more comment

Browser other questions tagged

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