Shniper
Shniper

Reputation: 854

Keypress in text input preventing typing

I have a text input that I want to execute a function when enter is pressed. I used if condition to determine if enter is pressed but this causes the user not to be able to type in the input box. What can I put in the else condition to allow them to type normally?

JsFiddle

function addItem(e) {   
    e.preventDefault();                         // Prevent form being submitted
    var text = $('input:text').val();           // Get value of text input
    var itemArr = text.split(',');                                                              
    var lngth = itemArr.length                  

    for(i = 0; i < lngth; i++)                  
    {
        $list.append('<li>' + itemArr[i] + '</li>');    // Add item to end of the list
        updateCount();                                  // Update the count
    } // End loop

    $('#addItems').val('');                         // Empty the text input
    return false;
}

$('#addItems').keypress(function(e) {
    if(e.which == 13) {
        addItem();
    }
    return false;
});

Upvotes: 1

Views: 1880

Answers (2)

Aya Salama
Aya Salama

Reputation: 1518

Jusr remove return false from the keypress event

You can see this Question

return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML.

and to prevent form from form being submitted, you can add onsubmit="return false" to the form

Demo

Upvotes: 0

Nalin Aggarwal
Nalin Aggarwal

Reputation: 888

Remove return false; from the keypress function.

$('#addItems').keypress(function(e) {
    if(e.which == 13) {
        addItem();
    }   
    else {
        return true;
    }

    return false;   
});

Upvotes: 1

Related Questions