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?
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);
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>');
}
}
$(document).on('click', '.addNewName', addNewUser);
Move function definition of addNewUser
out of $(document).on
. Replace it by its name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With