I’m writing a very simple terminal emulator(ish) app and I’m trying to build the functionality where up-arrow loads the previous command into the input. I’m close with what I have so far but I’m missing something in my math and it’s not working correctly…
command_history = {};
command_counter = -1;
history_counter = -1;
$('#term-command').keydown(function(e){
code = (e.keyCode ? e.keyCode : e.which);
// Enter key - fire command
if(code == 13){
var command = $(this).val();
command_history[command_counter++] = command;
history_counter = command_counter;
alert('Run Command: '+command);
$(this).val('').focus();
// Up arrow - traverse history
}else if(code == 38){
if(history_counter>=0){
$(this).val(command_history[history_counter--]);
}
}
});
…where #term-command is my input.
I’d say the issue is that you defined
command_historyas an object{}instead of an array[], since you are using it as an array.Also, I think you want to pre decrement with
--history_countersee this working fiddle:
http://jsfiddle.net/5DZxs/1/
So your javascript looks like: