3

I created a to do list and have it set to add the item when you click the add button but I want to make it to where you can press enter and here is my code:

function addListItem() {
    var text = $("#new-text").val();
    $("#todolist").append('<li><input type="checkbox" class="done"/>'+text+'<button                  class="delete">Delete</button></li>');
    $("#new-text").val('');
}

$(function() {
    $("#add").on('keypress' , addListItem);
}

please help

Huangism
  • 16,278
  • 7
  • 48
  • 74

4 Answers4

1

You can do something such this inside of your addListItem Function:

JS:

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

As your implementation:

function addListItem(event) {
    if(event.which == 13){
        var text = $("#new-text").val();
        $("#todolist").append('<li><input type="checkbox" class="done"/>'+text+'<button                  class="delete">Delete</button></li>');
        $("#new-text").val('');
    }
}

$(function() {
    $("#add").on('keypress' , function(event) { addListItem(event););
}
felipekm
  • 2,820
  • 5
  • 32
  • 42
0

Try this out:

function addListItem(event) {
    if(event.which == 13){

        var text = $("#new-text").val();
        $("#todolist").append('<li><input type="checkbox" class="done"/>'+text+'<button                  class="delete">Delete</button></li>');
        $("#new-text").val('');
    }
}

$(function() {
    $("#add").on('keypress' , addListItem);
}
MDiesel
  • 2,647
  • 12
  • 14
0

Check the keyCode in your function:

function something(event){
  if ( event.keyCode == 13 ) 
    alert( 'ENTER!');
}
ncksllvn
  • 5,699
  • 2
  • 21
  • 28
0

You need to get the keycode you pressed and check it is the ENTER key.

function addListItem(e) {
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (keycode == '13') {
        var text = $("#new-text").val();
        $("#todolist").append('<li><input type="checkbox" class="done"/>'+text+'<button                  class="delete">Delete</button></li>');
        $("#new-text").val('');
        $("#new-text").val('');
    }
});
Carlos Calla
  • 6,556
  • 2
  • 16
  • 23