4

When remove a predetermined character from the input keyup event fires twice. How can I prevent this?

HTML

<input type="text" id="search">

JS

var block = {
  'ch1': {
      'key':'/',
      'keycode':'191'
  },
  'ch2': {
      'key':':',
      'keycode':'186'
  },
  'ch3': {
      'key':'=',
      'keycode':'187'
  }
}

$('#search').on('keyup',function(){
  console.log(checkChar($(this)));
});

function checkChar($this){

  var txt  = $this.val(),
      flag = true;

  for(var i=0; i<txt.length; i++) {

    $.each(block,function(k,v){

      if (txt[i] === v.key) {
        $this.val(txt.slice(0,-1));
        flag = false;
        return false;
      }

    });

  }

  return flag;

}

JSBIN

https://jsbin.com/mirocepiqo/1/edit?html,js,output

midstack
  • 2,105
  • 7
  • 44
  • 73
  • 2
    The problem is that when you release the shift key, a keyup event is generated as well. Try to filter for the keys you are interested in. – GOTO 0 Sep 06 '16 at 07:19

1 Answers1

2

Pass event to function, check for event.shiftKey, if condition is true, return

$('#search').on('keyup',function(e){
  var res = checkChar(e, $(this));
  if (res !== undefined) {
    console.log(res);
  };

});

function checkChar(e, $this){
  if (e.shiftKey) {
    return
  };
  var txt  = $this.val(),
      flag = true;

  for(var i=0; i<txt.length; i++) {

    $.each(block,function(k,v){

      if (txt[i] === v.key) {
        $this.val(txt.slice(0,-1));
        flag = false;
        return false;
      }

    });

  }

  return flag;


}
guest271314
  • 1
  • 15
  • 104
  • 177