Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyup event prevents arrow keys in text field in Chrome

Please check this on Google Chrome browser:

jQuery('#tien_cong').keyup(function(e) {
  jQuery(this).val(jQuery(this).val().replace(".", ","));
  var sum = 0;

  var tien_cong = jQuery('#tien_cong').val();
  tien_cong = tien_cong.replace(/,/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="textfield" id="tien_cong" type="text" data-required="" data-type="text" name="tien_cong" placeholder="" value="" size="">

I try to replace . by , when user types somethings with . in a textbox.

On Chrome browser, when user press left cursor button on keyboard , it can not move.

enter image description here

Why?

like image 694
John Avatar asked May 04 '16 16:05

John


People also ask

How do I turn off my arrow keys on my browser?

To disable arrow key scrolling in users browser with JavaScript, we disable the default behavior for arrow keys and the space key. window. addEventListener( "keydown", (e) => { if ( ["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].

How do you code arrow keys in JavaScript?

To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.


1 Answers

Right now the input is updating every time a key is pressed. Testing to see if the character is a '.' before replacing will prevent the script from running when it doesn't need to, and prevents the cursor from resetting.

jQuery('#tien_cong').keyup(function(e) {
  if(e.which === 190) {
    jQuery(this).val(jQuery(this).val().replace(/\./g,","));
  }     
 
  var sum = 0;

  var tien_cong = jQuery('#tien_cong').val();
  tien_cong = tien_cong.replace(/,/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="textfield" id="tien_cong" type="text" data-required="" data-type="text" name="tien_cong" placeholder="" value="" size="">
like image 109
bags Avatar answered Nov 04 '22 11:11

bags