Reputation: 7782
I have a textbox and I want to prevent certain alphabet from been deleted but allow other to be deletable, I setup my code like this:
$("#myTextbox").keydown(function(e) {
var code = e.keyCode || e.which;
console.log(code);
if (code == 8) {
var valStr = $(this).val();
// how do I find which keystroke is being deleted?
}else if(!(code == 57 || code == 48 || code == 37 || code == 39 || code == 32)) {
e.preventDefault();
return false;
}
});
An example of the textbox value would be this:
( 1 and 2 ) or 3
The user would be able to delete "open bracket", "close bracket", "space", but nothing else.
Upvotes: 0
Views: 50
Reputation: 362
Well there is a logic flaw you need to deal with here. You are assuming that you can't highlight multiple characters and hit backspace once and delete a bunch.
My best suggestion would be to keep track of the input value constantly. So if it starts out as "( 1 and 2 ) or 3" and you they change it to "(1and)3", then compare it against the previous one and check if characters not in the whitelist were deleted. If so, put them back, or on the reverse side of it, take out only the ones they should take out.
In this example, "2" and "or" were not supposed to be taken out. Either put them back in, or instead use the previous string and take out the parts they took out that were allowed. After you craft this string, set the value of the input to that, but note that setting a value on an input will not trigger a change event. If you want to have a change event, that also tack on ".trigger('change');" onto the end of the value setting such that you would have this:
"$(this).val(new_string).trigger('change');"
As for determining the new_string, first I would define a function like this:
function is_character_deleteable(character)
{
if (character == "(" || character == " " || character == ")")
{
return true;
}
return false;
}
Then I would do this inside of your function:
Actually, after spending a bunch of time trying to come up with code for this, I discovered another flaw. Are you allowed to enter characters in? If so, then you have a world of problems.
I wonder if this would be better to attack this from a different angle. Obviously I don't know what you are doing specifically, but perhaps you could just use checkboxes/buttons to remove "(", ")", and " ".
Upvotes: 1
Reputation:
You need to:
1. Find element which is focused ( .is(":focus") )
2. Take value, find last character on every keypress and convert it to keycode:
var myString = $('elem').html();
var lastChar = myString.substr(-1);
var whatYouNeed = lastChar.charCodeAt(0);
I think that is all :).
Upvotes: 0