Make Backspace when pressing "+" key

Asked

Viewed 1,419 times

2

In a given input allow the user to put whatever content they want, but by pressing the key + will open a pop-up (that is working) with data coming from the database. What I am trying to do now is: When I press the key + open to pop-up, and at the same time I give a backspace in input to erase this + pressed into input.

Input:

<input type="text" id="inputIdCliente" class="form-control input-sm" onkeypress = "openSearchCliente(event)"/></td>

Function that opens the pop-up:

function openSearchCliente(e) {
        var unicode = e.keyCode ? e.keyCode : e.charCode;
        if (unicode == 43) {
            popupSearchCliente.Show(); //Abre pop up
            //Código para dar backspace na input (em falta)
        }
    }

What I really need is to give Backspace in input, I’ve already searched some things on the net and I haven’t found a solution that replicates what I want to do...

3 answers

5

You can test the keys that are pressed with keyCode, example:

$('input[type=text]').keydown(function(e) {
        // se a tecla pressionada for "+"
        if (e.keyCode == 107) {
          //abre o pop-up
          alert('abre pop-up');
          //limpa o "+" digitado
          $(this).val($(this).val().replace("+", ""));

        }
    });

Online Example

If you only want to remove the last character typed:

$('input[type=text]').keydown(function(e) {
        // se a tecla pressionada for "+"
        if (e.keyCode == 107) {
          //abre o pop-up
          alert('abre pop-up');
          //limpa o "+" digitado
          $(this).val($(this).val().substr(0, $(this).val().length-1));

        }
    });

Example 2

  • And if the input already has some value with the character +? In your code it would be removed together.

  • 1

    I edited my answer with the solution to the case cited.

3


I’m not sure if it’s the proper way, but I think it should work:

var t = $(this).val();
$(this).val(t.substr(0, t.length-1));

#Edit

How you are using Event keypress, just try with:

if (unicode == 43) {
    e.preventDefault();
}
  • Following your example: http://jsfiddle.net/cesarmiguel/Y9gVJ/

  • it is deleting the character wrong. Deletes the last inserted before the + and not the +

  • I added a second option, see if it works.

  • That’s right! I didn’t think the solution was through preventDefault... Thank you :)

0

Try making a return false;

Example:

function openSearchCliente(e) {
        var unicode = e.keyCode ? e.keyCode : e.charCode;
        if (unicode == 43) {
            popupSearchCliente.Show(); //Abre pop up
            return false;
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.