Search code examples
jquerykeypress

on keypress jquery issues


I am trying to make a little sample dropdown appear when a user enters a certain combination of letters in the form. I think I am having syntax/logic problems because I can't even get the alerts to work.

$(document).ready(function () {

   $("#inputt").keypress(

    function(event) {

        if (event.which == melee || MELEE) {

            alert("You typed MELEE");

        } else if (event.which == knuckle || KNUCKLE) {

            alert("You typed KNUCKLE");

        } else {

            alert("Neither!!!");
            $('.knuckle').hide();
            $('.melee').hide();

        }

   });

});

Here is the sample. https://jsfiddle.net/galnova/snp1hqr7/1/


Solution

  • So you have error in your code as there is no such event.which, if you see your console of developer mode, you can see error. So it must be either compairing the value of textbox by using $("#inputt").val() with the value 'melee'. It will do the trick

     if (event.which == melee || MELEE) {
    

    must be replaced by

     if ($("#inputt").val() == 'melee'||  $("#inputt").val() =='MELEE') {
    

    and subsequently for

    else if (event.which == knuckle || KNUCKLE)
    

    with

    else if ($("#inputt").val() == 'knuckle' || $("#inputt").val() ==KNUCKLE) 
    

    https://jsfiddle.net/aadi/2odkq3t8/

    Edit :- Also event you are using is keypress so it will be fired if text you have written is greater than melee and type another charatcer then it would be fired . It would be better if you use keyup event which is triggered when any key is released after pressing.