Firnas
Firnas

Reputation: 389

How to get the type word inside the input field once after pressing the Comma key and not after pressing space bar

I've a input field and I want the typed word to appear once after pressing the Comma key and not after pressing the space-bar. Currently I have is after pressing the space-bar. Thus how do I do it when I press only the Comma key.

Hope you understood my question.

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();
});

Upvotes: 0

Views: 122

Answers (1)

Alex McMillan
Alex McMillan

Reputation: 17952

The keyCode for the spacebar is 32. The keyCode for a comma is 188.

Replace

if(e.which===32)

with

if(e.which===188)

in your keypress handler.

Update

For your specific needs of preventing the comma from being displayed as well as allowing the enter key, try this:

$("#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();
    }
});

Upvotes: 2

Related Questions