在输入按键时触发jQuery事件?

时间:2014-11-22 07:44:28

标签: javascript jquery html forms

我正在尝试使用jQuery(我对此知之甚少)提交一个rails表单,并且已经成功设置了一个表单来提交单击提交按钮并运行回调(我相信这是正确的术语? ),但我也希望在进入时能让它发挥作用。

按照目前的情况,按Enter键会将数据提交到数据库,但不会运行命令来附加div或清除文本字段。我怎么能让这个发生,所以它对回车键和提交按钮的工作方式相同?我试图将代码包装在一个函数中,该函数将在命中输入时运行,但没有运气!

function runScript(e) {
if (e.keyCode == 13) {
    msg = json.msg;
    foreign = json.foreign_speaker;
    msg_translated = json.msg_translated;
    //The HTML that we will append to the document.
    html = "<div class='msg msg" + foreign + "'>" + msg +
            "</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"

    // Append new message.
    $('.chatmessages').append(html).fadeIn('fast');
    scrollToBottom(500)
    // Clear form with jquery.
    $('#message_msg').val('');
    $('#message_foreign_speaker').attr('checked', false);
}

}

我试过没有运气。

我当前的按钮工作JS文件:

var scrollToBottom = function(anim){
var myDiv = $(".wrap");
myDiv.animate({ scrollTop: myDiv[0].scrollHeight - myDiv.height() }, anim);
};

$(document).ready(function(){
scrollToBottom(0)
//JS to POST form
$('.submit').click(function() {
    var valuesToSubmit = $('.msgform').serialize();
    $.ajax({
        type: 'POST',
        url: window.location.href + '/messages', //sumbits it to the given url of the form
        data: valuesToSubmit,// { chat_id, <%= @chat.id %> },
        dataType: "JSON", // you want a difference between normal and ajax-calls
    })
    .done(refresherFunc)
    .fail(function(){
        alert("Error sending message. It would be nice to make this a flash error.");
    });
    return false; // prevents normal behaviour
})
});

var refresherFunc = function(json) {
// Get debugging goodies.
console.log(json);

// Set variables with JSON object data
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
        "</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"

// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}

1 个答案:

答案 0 :(得分:0)

使用jQuery&#39; submit()函数捕获表单提交事件,并在其中返回false。您提交表单的任何方式都会调用此函数(单击提交按钮或按Enter键)。返回false将阻止浏览器完成表单sumbittion,它允许您随意使用它。

参见示例:http://jsfiddle.net/vgk4wu46/