简体   繁体   中英

Prevent page reload on enter key pressed

i have the following input field:

<input type="text" id="txt_comment" class="form-control" placeholder="Skriv kommentar"> 

with this i have the following code

    $('#txt_comment').keyup(function(e){
    if(e.keyCode == 13)
    {
        addComment();
        return false;
    }
    e.preventDefault();
});

However when i press enter it still reloads the page. Can anyone tell me what im doing wrong?

Update

    function addComment()
{
    var comment = $('#txt_comment').val();
    {
        $.ajax({
            type: 'POST',
            url: '/Comment/addComment',
            dataType: 'json',
            data: {
                request: 'ajax',
                reciver:user_id,
                comment: comment
            },
            success: function (data)
            {
                $('#comment_list').prepend(
                    '                                        <li class="list-group-item animated fadeInRightBig">'+
                '        <p><b class="text">'+data['sender']+'</b>:'+
                '<br/>'+comment+' </p>'+
                '<input  type="hidden" class="timestamp" value="'+data["timestamp"]+'">'+
                 '   <small class="block text-muted timeSmall"><i class="fa fa-clock-o"></i></small>'+
                '</li>'
                )
                $('.timestamp').each(function()
                {
                    var text = $(this).next()
                    var timer = $(this).val();
                    var new_text = moment(timer, "YYYY-MM-DD- HH:m:ss").fromNow();
                    text.html(new_text);

                });
                $('#txt_comment').val('');

            }
        })
    }
}

And my function now look like this:

    $('#txt_comment').keyup(function(e){
    if(e.keyCode === 13)
    {
        addComment();
        e.preventDefault();
        return false;
    }
});

Still having page reloads

For quick reference: To solve the issue, add a hidden input field to your form.

This is a relic from the an older version of HTML :

When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.

The return is firing before the preventDefault call, just re-arrange them:

$('#txt_comment').keyup(function(e){
    e.preventDefault();
    if(e.keyCode === 13) {
        addComment();
        return false;
    }
});

Use the keydown function instead:

 $('#txt_comment').keydown(function(e){
    if(e.keyCode == 13)
    {
        addComment();
        return false;
    }
    e.preventDefault(); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM