lewis lewis - 5 months ago 7
jQuery Question

Preventing blank input not working

I'm trying to prevent blank input on an editable list item, I'm using the same code I use somewhere else but for some reason it is not working.

I have:

if(folderName == "" || folderName == " " || folderName.charAt(0) == " "){
$(this).remove();
}


It is removing the item if I do not type anything, though if I enter a blank space it doesn't call the remove.

Strange thing is I am using this exact same code in a different area and it's working fine.

Here is the full function:

$(document).on('focusout', '#folders li', function(){ //add class when lose focus/shorten name if too long
var folderName = $(this).text();
$('#folders li').removeAttr('contenteditable');
$('#folders li').removeClass('active-tab');
$(this).addClass('active-tab');
if(folderName.length > 15){
$(this).attr('title', $(this).text());
shortFolderName=folderName.substring(0,15) + '...';
$(this).text(shortFolderName);
}
else if(folderName.length <= 15){
$(this).text(folderName);
$(this).attr('title', $(this).text());
}
if(folderName == "" || folderName == " " || folderName.charAt(0) == " "){
$(this).remove();
}
console.log(folderName);
})


html:

<div id="tabs">
<ul id="folders">
<li class="active-tab" >All Notes</li>
<li>Work</li>
<li>Personal</li>
<li id="add" class="glyphicon glyphicon-plus"></li>
<ul>
</div>

Answer

You can also use the .trim() function and then check the string's length.

if(folderName == "" || folderName.trim().length === 0){
    $(this).remove();
}

Note: The trim() function removes whitespace from both ends of a string.

MDN

Comments