nanobash
nanobash

Reputation: 5500

up and down arrows javascript

I'll explain what to do next , while here is html code =>

<fieldset>
         <legend>Get&nbsp;Data&nbsp;Ajax</legend>
         <form name="ajax" method="get" action="getData.php">
         <input type="text" name="getName" id="getName">
         </form>
         <div class="resBox" id="resBox"></div> <!-- this div is where results are placed-->
</fieldset>

I've written ajax script which is retrieving some info from mysql database onkeyup in input field and then I have done also how to collapse info down from this field. Here is the situation , can anyone explain how to do (when info already collapsed) that in up and down arrows could movement into info ? Please give an advice how to do that ?

In conclusion I am interested in how to handle javascript key events. please give some examples, thanks :)

I've tried like so but it is not working =>

var key;
if (window.event){
    key = e.keyCode;
} else {
    key = e.which;
}

if (key==13){ // enter for example 
    alert("something");
}

Upvotes: 0

Views: 1835

Answers (1)

sransara
sransara

Reputation: 3484

This JS code should probably work in your context. See a working Demo here.

el = document.body;
if (typeof el.addEventListener != "undefined") {
    el.addEventListener("keydown", function(evt) {
        doThis(evt.keyCode);
    }, false);
} else if (typeof el.attachEvent != "undefined") {
    el.attachEvent("onkeydown", function(evt) {
        doThis(evt.keyCode);
    });
}

function doThis(key) {
    switch (key) {
        case 13:
            alert('enter pressed');
            break;
        case 27:
            alert('esc pressed');
            break;
        case 38:
            alert('up pressed');
            break;
        case 40:
            alert('down pressed');
            break;
    }
}

First of all consider reading this Stackoverflow question.
And you can read this MDN entry too.

Upvotes: 2

Related Questions