I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Javascript: onkeyup not getting along with onsubmit

I have 2 functions attached to even listeners in a form. An onsubmit attached to a <form> and an onkeyup attached to an <input> within the form.

The form has no search button, user must hit enter to submit the form. Problem is that hitting enter triggers the onkeyup AFTER the onsubmit.

the onkeyup function shows a message to "hit enter to search", then the onsubmit is supposed to replace that text with a loading bar until AJAX return the results. Instead of showing my loading bar, the script show the text "press enter to search".

Here is a simplification...

<script>
    function doThings(){
        document.getElementById('results').innerHTML = "<img src='loading.gif' />";
        //Ajax Stuff
        return false;
    }
    function checkThings(){
        var someCondition = true;
        if(someCondition){
            document.getElementById('results').innerHTML = "Press ENTER to search.";
        }
    }
</script>
<form onsubmit="return doThings()">
    <input type="text" id="q" onkeyup="checkThings();" />
</form>
<div id="results"></div>

What can I do to ensure that the onsubmit function is executed AFTER the onkeyup function, otherwise prevent the onkeyup function from executing when the ENTER key is pressed?

Upvotes: 1

Views: 603

Answers (2)

ataman
ataman

Reputation: 2664

Simple workaround is to wrap showing loading bar in setTimeout call to execute it in next event loop:

setTimeout(function() {
  document.getElementById('results').innerHTML = "<img src='loading.gif' />"
}, 0);

EDIT: Another way, if you, actually, want to prevent the onkeyup function from executing when the ENTER key is pressed is to check keycode in event handler. "Enter" key code is 13:

<input type="text" id="q" onkeyup="if (event.keyCode !== 13) checkThings();" />

Upvotes: 1

Arthur Weborg
Arthur Weborg

Reputation: 8580

One way you can prevent this execution is by setting a boolean in your doThings() function stating an Ajax call was made. when the Ajax call is returned you can flag that boolean off.

var submitted = false; 
function doThings(){
    document.getElementById('results').innerHTML = "<img src='loading.gif' />";
    submitted = true;
    //Ajax Stuff
    //on Ajax success make sure to set submitted back to false
    return false;
}
function checkThings(){
    var someCondition = true;
    if(someCondition && !submitted){
        document.getElementById('results').innerHTML = "Press ENTER to search.";
    }
}

Upvotes: 1

Related Questions