I am working on todos. And, I was looking for submitting Todos through ajax
on pressing 'enter' key
.
It is working fine. But, there is one problem. It submits data 2 times for every press on 'enter' key. I don't have any submit button. I wanted to have on pressing enter key in textbox (#todos-t_description
).
<form id="create-todos-form" action="/misc/todos/index" method="post">
<input id="todos-t_description" class="t_description form-control" name="Todos[t_description]" type="text">
<select id="todos-t_case_id" class="form-control" name="Todos[t_case_id]">
<option value="">Related to case</option>
</select>
</form>
I Used.
<script>
window.addEventListener("DOMContentLoaded", function() {
jQuery(document).ready(function($){
$('.t_description').keydown(function (event){
if (event.keyCode == 13) {
$('#create-todos-form').submit();
}
});
$('#create-todos-form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
url: "/misc/todos/create",
type: "POST",
data: formData,
success: function (data) {
$("#todos-t_completed_date").blur();
$('tbody').append(data);
$('.t_description').val("");
$('#todos-t_completed_date').val("");
$('.noTodos').hide();
},
error: function () {
alert("Problem Ocurred");
}
});
});
});
}, false);
</script>
I don't know what is happening in code. If I put alert before e.preventDefault();
. Alert message coming twice too on single 'enter' key press. Even I focus to other textbox after getting success message. But, No. It didn't worked. Any Hint/Suggestions.