Search code examples
javascripthtmlbuttonenter

Enter key for button


I have changed my code from this discussion in such a way that if I press enter it comes to first button and if I press tab it goes to second button. But now my problem is, from the first button if I press enter it is not invoking that button and if I press tab from the second button again it is not going to first button. So I need these things to happen:

1) From first/second button if I hit enter, the button should invoke(click)

2) If I hit tab from second button it should go between first and second.

This is the code that I have used.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="hel">hello</button>
<button id="hel1" >hello1</button>
<script>
    $(function() {
        $(document).keydown(function(e) {
            if (e.keyCode == 13) {
                $("button#hel").focus();
            }
            if (e.keyCode == 9) {
                $("button#hel1").focus();
            }
        return false;
        });
    });
</script>

What change should I make?


Solution

  • Alexis is close, but you want the focus to go to the button after the first enter, so what you want to do is set a detector. You also want it to cycle through the buttons when you press tab, going back to the top if they are on the last when they prss tab. If a button is focused, click it, if not, got to the first button.

    Try this:

    $(function() {
    	$(document).keydown(function(e) {
    		var currentBtn = $(".mybtn:focus"),
    		inputs = $(".mybtn"),
    		currentIndex = inputs.index(currentBtn),
    		next = inputs.filter(function (index) {
    			if (currentIndex < inputs.length) {
    				return index == currentIndex + 1;
    			} else {
    				return index == 0;
    			}
    		});
    
    		if (e.keyCode == 13) {
    			if (currentBtn.length) {
    				currentBtn.click();
    			} else {
    				$(".mybtn").first().focus();
    			}
    		}
    		if (e.keyCode == 9) {
    			if (currentBtn.length) {
    			if (currentBtn.is(".mybtn:last")) {
    					$(".mybtn").first().focus();
    		} else {
    					next.focus();
    				}
    			} else {
    				$(".mybtn").first().focus();
    			}
    		}
    		return false;
    	});
    });
    
    $("button#hel").on('click', function(){
    	alert("hello press");
    });
    
    $("button#hel1").on('click', function(){
    	alert("hello1 press");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="hel" class='mybtn'>hello</button>
    <button id="hel1" class='mybtn' >hello1</button>