i have a form like this :
I think it may be better to do this on the submit of the form. Browsers do the whole "enter" thing for you so you don't have to worry about it.
Add id
to the <form>
tag, and change the type from button
to submit
:
<form method="post" id="myForm">
<input type="text" name="msg" id="chat_in" >
<input type="submit" name="bt" id="bt" value="Click Me">
</form>
Update you Javascript:
$('#myForm').submit(function() {
SendData();
});
Here is the JSFiddle
$("#chat_in").keyup(function(event){
if(event.keyCode == 13){
//call send data function here
SendData();
} });
try this
Move out SendData
from document.ready
function SendData() {
$.ajax({
url: "save.php",
type: "post",
data: "msg="+$('#chat_in').val(),
dataType: 'json',
success: function(){
alert("Sent");
},
error:function(){
alert("failure");
}
});
}
$(document).ready(function () {
$('#chat_in').keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
SendData();
}
});
$('#bt').click(function() {
SendData();
});
});
if anyone have same problem , just remove form
and use button
in this case your html and javascript should be something like this :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>final</title>
<script type="text/javascript" src="jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
function SendData() {
$.ajax({
url: "save.php",
type: "post",
data: "msg="+$('#chat_in').val(),
dataType: 'json',
success: function(){
alert("Sent");
},
error:function(){
alert("failure");
}
});
}
$('#chat_in').keypress(function(e) {
if(e.keyCode == 13) {
alert('You pressed enter!');
SendData();
}
});
$('#bt').click(function() {
SendData();
});
});
</script>
</head>
<body>
<input type="text" name="msg" id="chat_in" >
<input type="button" name="bt" id="bt">
</body>
</html>
Please try to use keyup function as "keypress" function behaves differently in different browsers.