Reputation: 20555
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
Upvotes: 0
Views: 206
Reputation: 2002
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.
Upvotes: 1
Reputation: 2743
Use the keydown function instead:
$('#txt_comment').keydown(function(e){
if(e.keyCode == 13)
{
addComment();
return false;
}
e.preventDefault(); });
Upvotes: 0
Reputation: 2258
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;
}
});
Upvotes: 0