jQuery를 사용하여 레일스 양식을 제출하려고하는데 제출 버튼을 클릭하여 제출할 양식을 설정하고 콜백을 실행하는 데 성공했습니다. 올바른 용어라고 생각합니다. , 그러나 나는 또한 그것을 타격을 할 때 작동하도록하고 싶습니다.Enter 키를 눌렀을 때 jQuery 이벤트가 발생합니까?
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);
}
고마워요! 이로 인해 모든 것이 완벽하게 이루어졌습니다. – neill