按空格键后,如何在输入字段内获取类型字,而不是按空格键

时间:2015-06-05 05:54:43

标签: jquery html css

我有一个输入字段,我希望键入的单词在按下逗号键后出现一次,而不是在按空格键后出现。目前我已经按下了空格键。 因此,当我只按下逗号键时,我该怎么做呢。

希望你理解我的问题。

HTML

<div id="wrapper">
<input type="text" id="txtNames" placeholder="Type name here"/>
</div>

CSS

.tagsDiv
{
background-color:rgb(165, 215, 175);
color:black;
display: inline-block;
padding:5px;
height:30px;
margin:10px;
border-radius:5px;
}

.innerBody{
display:inline-block;
padding: 5px;
}
.close{
margin-left:-5px;
position:absolute;
margin-top:-7px;
text-decoration: none !important;
}
#wrapper{
width:400px;
min-height:200px;
border:black 2px solid;
}
#txtNames{
border:none;
outline:none;
padding:15px;
}

JS

function createTag(vals)
{
var html='<div class="tagsDiv">'
         +'<div class="innerBody">'+vals.trim()+'</div>'
         +'<a href="#" class="close">x</button></div>';
$(html).insertBefore('#txtNames');
$('#txtNames').val('')
}


$("#txtNames").on('keypress',function(e){
if(e.which===32)
{
    if($(this).val().trim()!=='')
    {
    setTimeout(function(){
        createTag($('#txtNames').val());   
    },0);
    }
}
});

$(document).on('click','.close',function(){
$(this).parents('.tagsDiv').remove();
});

1 个答案:

答案 0 :(得分:1)

空格键的keyCode为32.逗号的keyCode为188。

替换

if(e.which===32)

if(e.which===188)

keypress处理程序中。

更新

针对您阻止显示逗号以及允许enter密钥的特定需求,请尝试以下操作:

$("#txtNames").on('keydown', function (e) {
    // Grab the textbox value
    var value = $(this).val();

    // Check for ENTER or COMMA
    if (e.which === 13 || e.which === 188) {
        if(value) {
            createTag(value);   
        }

        // Cancel the event, preventing the ',' from 
        // appearing in the input box
        e.preventDefault();
    }
});