keypress event vs click event

3.9k views Asked by At

My eyes are destroyed so this question will be specific to keyboard events.

When I define a handler for a click event for a button, like this:

$("#button").on("click", function() {
    alert("clicked");
});

Since I can't use the mouse (and I think most web applications use the click event to execute an html element), I tested this event by going to the button and pressing enter on it. The event fired successfully. Since then I came to believe that pressing the enter key simulates a click event to an html element. I've been executing submit buttons lots of times so there is no reason to believe that is not the case.

Now, I am creating a textbox which needs to be populated with a value when accessed. So I did this:

$("#text").on("click", function() {
    alert("clicked");
});

However, pressing enter on it no longer works, no value appears. But when some other human clicks the element using a mouse, the event fires successfully.

Here is the code I am working on:

I am using jquery-ui's autocomplete. I'd like the textbox to be populated when the user goes inside the textbox. I press enter to go inside...

$( "#tags" ).autocomplete({
    source: names,
    minLength: 0,
    select: function( event, ui ) {
        var index = names.indexOf($(this).prop("value"));
        $(this).val("");
        $("#selected").append("<li>"+names[index]+
        "<input type='hidden' id='id' value='"+ids[index]+"'/>"+
        "<a href=''>remove</a></li>");
        ids.splice(index, 1);
        names.splice(index, 1);
        return false;
    }
}).on("click", function(event) {
    $(this).autocomplete("search", $(this).val());
});

Is there really a difference between pressing enter and a mouse click? What should I do?

2

There are 2 answers

2
AudioBubble On BEST ANSWER

Catching the keypress event and testing for 'enter' is the best way to deal with this. The reason why the buttons execute on enter without this is due to them being of type 'submit'.

0
Andre Polykanine On

Basically, it is not a good idea to fire onClick on edit boxes since you won't have keyboard alternatives this way without more efforts.
As you are blind like me (I supposed this from your question), you are probably using some screen reading software. In screen readers, Enter usually simulates mouse click but. But JAWS for Windows, for instance, adds even more flexibility allowing you to adjust what to do when Enter key is pressed: simulate a mouse click or send Enter to the system.
So, in your case I'd make a button that would fire your onClick event.