Reputation: 198
i have a form like this :
<form method="post">
<input type="text" name="msg" id="chat_in" >
<input type="button" name="bt" id="bt">
</form>
i want to send data when user pressing enter or clicking on button
it's work when user click on button , but it doesn't work when user pressing enter on chat_in
here is my javascript :
$(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.which == 13) {
alert('You pressed enter!');
SendData();
}
});
$('#bt').click(function() {
SendData();
});
});
how can i solve this problem ?
Upvotes: 0
Views: 3634
Reputation: 92
Please try to use keyup function as "keypress" function behaves differently in different browsers.
Upvotes: 0
Reputation: 198
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>
Upvotes: 1
Reputation: 2039
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
Upvotes: 0
Reputation: 170
$("#chat_in").keyup(function(event){
if(event.keyCode == 13){
//call send data function here
SendData();
} });
try this
Upvotes: 1
Reputation: 5222
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();
});
});
Upvotes: 0