Flama
Flama

Reputation: 868

Function being called several times?

So I have the following function which calls another one called 'change_name(event, name)'. Turns out 'change_name' is called more than just one time? The variables it uses have mixed values.

function input_name(event, name) {
    event.stopPropagation();
    name.style.backgroundColor = "transparent";
    window.localStorage.removeItem("oldname");
    window.localStorage.setItem("oldname", name.value);
    $(this).click( function()
    { 

    change_name(event, name); } );

    $(name).keydown(function(event){
        if(event.keyCode == 13){
            change_name(event, name);
        }
    }); 
}


 function change_name(event, element) {
      event.stopPropagation();
      var name_input = element;
      var name = name_input.value;
      var oldname = window.localStorage.getItem("oldname");
    // new_name.innerHTML = name;
     console.log("Nombre viejo: " + oldname);
     console.log("Nombre nuevo: " + name);

 }

input_name function is an attribute of an element

 input.setAttribute("onclick", "input_name(event, this);");

Why are my values getting mixed up?? Any ideas?

Upvotes: 0

Views: 47

Answers (1)

joelnet
joelnet

Reputation: 14261

You are adding a new click and keydown event on every click of input. These events need to be added outside of the click event.

// on click, input_name is called
input.setAttribute("onclick", "input_name(event, this);");

// this function is called on every click of input
function input_name(event, name) {

  // new events are added on every click
  $(this).click(function() {/* ? */});
  $(name).keydown(function(event) {/* ? */}); 
}

So do something like this instead:

// on click, input_name is called
input.setAttribute("onclick", "input_name(event, this);");

// events are added once
$(input).click(function() {/* ? */});
$(input).keydown(function(event) {/* ? */}); 

// this function is called on every click of input
function input_name(event, name) {
  /* ? */
}

also look into why you are using $().click to create an onclick and also input.setAttribute("onclick", ...) Since you have jQuery, prefer using $().click over setting the attribute.

Upvotes: 1

Related Questions