I need to know why this function is not appending my error message when referenced to a variable. I tried returning some value like "false" but still not working. Please help me learn something here.
function checkName(el)
{
if (/^[a-zA-Z ]+$/.test(el.val()))
{
return null
}
return el
}
$(document).ready(function()
{
$('button[name=btn-submit]').on('click', function(e)
{
e.preventDefault();
var err = {
fn: checkName($('input[name=fn]')),
mn: checkName($('input[name=mn]')),
ln: checkName($('input[name=ln]'))
}
var isSubmit = function(){
for (var key in err) {
if (err.hasOwnProperty(key)) {
if(err[key] !== null)
{
var parent_div = err[key].parent().closest('div');
parent_div.append('<p id="p-error" class="error-msg">test</p>');
}
}
}
}
console.log(isSubmit);
//
1 Answer 1
You're never calling your function that processes the err object. You're just creating it and assigning that function to the isSubmit variable.
To call it, you'd need to add () to the end, either to the end of the function expression (if your goal is to assign the result of calling it to isSubmit), or after isSubmit in the console.log (if your goal is to call it there).
E.g., either
var isSubmit = function(){
for (var key in err) {
if (err.hasOwnProperty(key)) {
if(err[key] !== null)
{
var parent_div = err[key].parent().closest('div');
parent_div.append('<p id="p-error" class="error-msg">test</p>');
}
}
}
}(); // <== Here (could be pretty easy to miss seeing this, though)
or
console.log(isSubmit());
// Here ------------^^
{on the same line of the structure, or on the next line) makes it easier to read and debug your code. In JavaScript, the overwhelming convention is to have the{on the same line, but that's just convention. (Just whatever you do, don't put a line break afterreturnbefore what you're returning; automatic semicolon insertion will bite you.)