Search code examples
jqueryformsappendtextinput

jQuery append value of text field to list on form submit


I'm trying to create an extremely simple comment form for a demo; add some text in a text field, submit, add value to a list. It works when I use a button and an on click event like so:

<script>
$(".add-comment").click(function (e) {
var add = $('#comment-body').val();
$('.comments').append('<li>' + '<h4>Name</h4> ' + add + '</li>');
});
</script>

<form>
<input type="text" id="comment-body" />
<button type="button" class="add-comment">Submit</button>
</form>
<ol class="comments"></ol>

But this is for a mobile demo, so I don't want a button at all. I just want the comment to be posted when the user hits the return key. I tried removing the button, and editing the script like so, but it doesn't work:

$("form").submit(function (e) {
var add = $('#comment-body').val();
$('.comments').append('<li>' + '<h4>Name</h4> ' + add + '</li>');
});

Any ideas what I'm doing wrong?


Solution

  • OK, for anyone who stumbles on this in the future, there's a far easier way to do it. All you need to do is detect when someone hits the enter key. You don't need to use a form at all. Here it is:

    <ol class="comments"></ol>     
    <input type="text" id="comment-body" placeholder="add comment here" />          
    <script>     
    $('#comment-body').keydown(function (e){     
    if(e.keyCode == 13){     
    var add = $('#comment-body').val();     
    $('.comments').append('<li>' + '<h4>Name</h4> ' + add + '</li>');     
    }})     
    </script>