stack stack - 27 days ago 5
Javascript Question

How can I call a already defined function on keypress?

Here is my code:

$(document).on('click', '.addNewName', function addNewUser() {
var names = $('.compare_list td:nth-child(1)').map(function () {
return $(this).text().trim();
}).get();
var newname = $('.newname').val();

if ($.inArray(newname, names) != -1) {
alert('this name is duplicate');
} else if (newname == '') {
alert('enter a name');
} else {
$('.compare_list > tbody:last-child').append('<tr><td>'+newname+'</td><td><i class="fa fa-times" aria-hidden="true"></i></td></tr>');
}

})

// add user by Enter button
$("#newnam").keypress(function (e) {
if (e.keyCode == 13) {
addNewUser();
}
});


When I click on
.addNewName
my code works as well. But when I press enter on keypress of
#newname
, it throws this error:


Uncaught ReferenceError: addNewUser is not defined(…)


Does anybody how can I fix it?

Answer

At javasctipt at Question addNewUser is not defined outside of the scope of addNewUser function.

Define addNewUser as a named function, set as event handler at .addNewName click event, call and possibly pass parameters to addNewUser within #newnam keypress event.

   function addNewUser() {
      var names = $('.compare_list td:nth-child(1)').map(function() {
        return $(this).text().trim();
      }).get();
      var newname = $('.newname').val();

      if ($.inArray(newname, names) != -1) {
        alert('this name is duplicate');
      } else if (newname == '') {
        alert('enter a name');
      } else {
        $('.compare_list > tbody:last-child')
        .append('<tr><td>' + newname 
          + '</td><td><i class="fa fa-times" aria-hidden="true"></i></td></tr>');
      }

    }

    // add user by Enter button
    $(document).on("keypress", "#newnam", function(e) {
      if (e.keyCode == 13) {
       addNewUser() // set `this`, pass parameters to `addNewUser`
      }
    });

    $(document).on('click', '.addNewName', addNewUser);