Search code examples
javascriptphpjqueryhtmlajax

disabling arrow keys in javascript while using onKeyUp


i searched for this but i was not able to find a question..maybe i did not used appropriate keyword..if it is duplicate i am sorry

Here is my question.I had written a code in HTML, PHP, AJAX and Javascript..I am checking for online username availability in the database after each character is entered.The problem is that onKeyUp is detecting arrow keys also as input

left and right arrow keys

So when i try to insert a character in between the text entered in the textfield the cursor automatically moves to the end of the textfield..so modification in between the text is not possible.

Here is my HTML code

<input type = "text" name = "txt_username" id = "user" onKeyUp = "check_username(this.value)">
<span id = "check" style = 'color: green; font-size: 20px'> </span> <br>

and here is the check_username() function

function check_username(str) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var arr = xmlhttp.responseText.split("^");
            document.getElementById("user").value = arr[1];

            if (arr[0] == 2) {
                $("#check").html("Enter a username of at least 4 characters");
            } else if (arr[0] == 1) {
                $("#check").html("Username already exists");
            } else {
                $("#check").html("Username available");
            }
        }
    }
    xmlhttp.open("GET", "username_check.php?txt_username=" + str, true);
    xmlhttp.send();
}

and here is my username_check.php

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("company");

$username = ($_REQUEST['txt_username']);
$a = 0;

if (strlen($username) < 4) {
    $a = 2;
    echo $a . "^" . $username;
} else if (checkexistence($username)) {
    $a = 1;
    echo $a . "^" . $username;
} else {
    $a = 0;
    echo $a . "^" . $username;
}

function checkexistence($username) {
    $check = mysql_query("select username from employee");

    while ($row = mysql_fetch_array($check)) {
        if (strcmp($username, $row['username']) == 0) {
            return true;
        }
    }
    return false;
}
?>

How can I somehow manage(by disabling or keeping some check) the arrow keys so that text can be inserted in between??


Solution

  • Here is it:

    <input type = "text" name = "txt_username" id = "user" onKeyUp = "if(!(event.keyCode>36&&event.keyCode<41)){check_username(this.value)}">