Johan Nordli
Johan Nordli

Reputation: 1230

Enter in input field focus nearest button in IE9

I have a input field and a button in the code below.

I have write some javascript code to catch the keyup and show a alert if its the Enter key.

This work fine in Firefox, but in IE9 will a enter click in the input field resulted in that the button becomes focused and the keyUp trigger in javascript will not be fired.

Anyone have suggestions for solution?

jsfiddle: http://jsfiddle.net/c46khq2x/1/

HTML:

<input type="text" class="js-field-click"/>

<button class="js-button-click">Button</button>

javascript ( JQuery ):

 $( document ).ready(function() {


      $(".js-field-click" ).keyup(function(e) {
         var val = $(this).val();
         var code = e.which;

         if(code==13){
            alert("field enter");
         }
      });

     $(".js-button-click").click( function() {
            alert("button click");
     });
 });

Upvotes: 1

Views: 345

Answers (3)

Johan Nordli
Johan Nordli

Reputation: 1230

I find a solution, it seems that IE9 select the next button within the form, so by wrapping text field in a form and leave the button outside of the form, then IE9 will not selecting the button and the script will work

<form>
    <input type="text" class="js-field-click"/>
</form>    

<button class="js-button-click">Button</button>

Upvotes: 1

Omar Elawady
Omar Elawady

Reputation: 3350

I emulate Internet explorer 9 and manipulated your code to be:

 $( document ).ready(function() {


  $(".inp" ).keyup(function(e) {alert('keyup triggered');
     var val = $(this).val();
     var code = e.which;

     if(code==13){
        alert("field enter");
     }
  });

 $(".but").click( function() {
        alert("button click");
 });
});

and HTML:

 <input type="text" class="inp"/>

 <button class="but">Button</button>

when I type a letter it alerts "keyup triggered". but when I click Enter key. it sends click event to button (but) and it alerts "button click". but it doesn't send keyup event to input

Upvotes: 0

Viraj Nalawade
Viraj Nalawade

Reputation: 3227

Hi there is a issue with the code. there are couple of things you need to correct. You can try below to check it...

$( document ).ready(function() {


      $(".js-field-click").on('keydown', function(e) {
         var val = $(this).val();
         var code = e.which;

         if(event.which == 13){
            alert("field enter");return false;
         }
      });

     $(".js-button-click").click( function() {
            alert("button click");
     });
 });

some points to note:-
1. prefer to change the selector to window
2. Use .on() function
3. Add a return false; to stop the event from bubbling.

Upvotes: 1

Related Questions