I have a table listing with a ‘notes’ field in each row. I’d like to be able to update these using ajax and display a little message once they have been updated, but I’m struggling to figure out the correct code.
My plan was to capture a key press, and pass the note ID into a timer, which would be reset every time the user presses a key so it will only run once they’ve stopped typing for 1 second. The problem is, with multiple notes on the page I need to pass it into an array and reset the timer on each one, if this is even possible?
Here’s my code:
var waitTime = 1000;
var click = false;
var timers = new Array();
$('.notes').keyup(function(){
var timerVariable = $(this).attr('id').split("-");
timerVariable = timerVariable[0];
timerVariable = timerVariable.replace('note', '');
timers.push(timerVariable);
timers[timerVariable] = timerVariable;
if(click==false){
var id = $(this).attr('id');
if(click==false){
click= true;
timerVariable = setTimeout(function(){doneTyping(id)}, waitTime);
}
}
});
$('.notes').keydown(function(){
for (var timer in timers) {
clearTimeout(timer);
}
click = false;
});
function doneTyping (id) {
var staffNo = id.split("-");
staffNo = staffNo[0];
staffNo = staffNo.replace('note', '');
var data = 'data='+id+'¬e='+$('#'+id).val();
$.ajax({
url: "update-notes.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
jGrowlTheme('mono', 'Updated ' + staffNo, 'Thank you, the note has been updated.', 'tick.png');
}
});
}
I’m wondering if the problem is maybe with the way I’m calling the for loop, or something else? Any advice would be very welcome, thank you!
It is not a direct answer to your problem but I would personally make a jquery plugin out of your code that you would use like this:
Each “note field” would have it’s instance of the plugin encapsulating a timer dedicated for each field. No need to worry about storing in arrays and such.
There are plenty of plugin patterns and boilerplates out there like this one and this other one.
Here is a sample implementation. I’ve used the one boilerplate and merged it with the jquery ui bridge code (which checks for private methods, re-using a previous plugin instance or instantiating it correctly):
Working DEMO