Alosyius
Alosyius

Reputation: 9151

Javascript onkeyup being fired twice sometimes

For some reason my onkeyup seems to be fired twice for some people on IE9.

My current function looks like this:

document.getElementById("chatboxtextarea").onkeyup=function(e) {
    e = e || window.event;
    var msg = document.getElementById('chatboxtextarea').value;
    if(e.keyCode != null) {
        if (msg.replace(/\r/g, '\\\\r').replace(/\n/g, '') != "" && e.keyCode == 13) {
            var textarea = document.getElementById('chatboxtextarea');
            textarea.value = '';

            var d = new Date();
            var curr_hour = d.getHours();
            var curr_min = d.getMinutes();
            var tD = curr_hour + ":" + curr_min;


            var url = 'http://domain.com/sub/' + kanal + '/' + encodeURIComponent(_aNM) + '/' + encodeURIComponent(_sid) + '/' + encodeURIComponent(_aID) + '/' + encodeURIComponent(_pMsg) + '/' + encodeURIComponent(msg.replace(/\r/g, '').replace(/\n/g, '')) + '/' + encodeURIComponent(_hits);
            var data = {};
            var callback = function (data) { };
            J50Npi.getJSON(url, data, callback);                            
        } else if (msg.replace(/\r/g, '\\\\r').replace(/\n/g, '') == '') {
            var textarea = document.getElementById('chatboxtextarea');
            textarea.value = '';
        }           
    }
};

This is for a basic chat input field. Problem is that the server receives two messages from these IE9 users (sometimes).

How would i add a check to see if people have already written a message in the last 1 seconds? Like a spam prevention function.. i guess that would solve the problem?

Any ideas?

Upvotes: 0

Views: 253

Answers (1)

rsnickell
rsnickell

Reputation: 1262

Is it possible people are pressing the enter key twice fairly quickly?

Any time I have to perform an async operation, I debounce the input.

Just after your keycode == 13 check, first check to see if the textares is already disabled, if it is disabled ignore any further processing. Second, set the textarea to disabled. Third, remove the disabled attribute upon success of J50Npi.getJSON();

textarea.setAttribute("disabled","disabled");
textarea.removeAttribute("disabled");

http://jsfiddle.net/Tnwje/1/

Upvotes: 2

Related Questions