当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - 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>

网友答案:

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

网友答案:

Check the space like this:

folderName.indexOf(' ') >= 0

So your check should be like this:

if(folderName == "" || (folderName.indexOf(' ') >= 0)){
    $(this).remove();
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: