-1

I have an input form that has a jQuery event applied to it that creates square brackets around the users input. The issue is that the event prevents the ability to use backspace to delete the text. I'm looking for a way to check if backspace is being pressed and prevent the code from runnning.

jQuery Script

function test(obj) {
var oldVal = obj.val().replace(/\[/g,\'\');
oldVal = oldVal.replace(/\]/g,\'\');
var val = \'[\' + oldVal + \']\';
obj.val(val);

Input Form

oninput="test($(this));"
Jay
  • 11
  • 7
  • 2
    `test($(this))`? I think `$(this)` is undefined there. Can you not just do `if (e.which == 8) return false` (8 being backspace) – putvande Aug 14 '14 at 14:34
  • it makes it easier to answer questions like this if you add a jsfiddle to your question. http://jsfiddle.net/ – Zach Spencer Aug 14 '14 at 14:34
  • Heres a jsfiddle that needs to be slightly modified: http://jsbin.com/gaxewatu/22/edit?html,js,output – Jay Aug 14 '14 at 14:41

1 Answers1

2
 function test(obj,e) {  
      if(!(e.which == 8)){
           var oldVal = obj.val().replace(/\[/g,'');
           oldVal = oldVal.replace(/\]/g,'');
           var val = '[' + oldVal + ']';
           obj.val(val);
      }
 }

and pass event as parameter ..

 <input class="text-box" onkeyup="test($(this),event)">
Alok
  • 512
  • 1
  • 3
  • 15