Reputation: 697
I have a textbox. The only things I want the user to be able to enter are parentheses. They should also only be able to delete parentheses. I'm having a ton of trouble doing this though.
Right now I have a function like this:
'#myTextArea input': function (el, ev) {
}
I used input so it would handle people pasting.
I'm not sure how to find the character typed from this though. I especially don't know how to make sure only a parentheses was deleted. Anyone know of a good way to do this?
Edit To clarify, the textbox is already populated with text. The user should just be able to add and remove parentheses to the text already there.
Edit2
I got it working so the user can ONLY enter parentheses. This does not take into account pasting, and does not deal with deleting. Still have no idea how to do that.....
'#myTextArea keydown': function (el, ev) {
if ((ev.keyCode != 48 && ev.keyCode != 57) || ev.shiftKey == false){
return false;
}
}
Upvotes: 2
Views: 511
Reputation: 4996
One possible solution is do it programatically in keyup event. I show only the case when inserting (by pressing a key or pasting).
Whether it was character key pressed or Ctrl-V, in general, there is a substring being inserted into a string. The caret position will be at the end of that substring.
My algorithm finds that substring as the string between two positions:
Then it filters the string using function filterString that will replace all non parenthesis symbols with ""
And finally updates input value to longest common prefix + filtered string + text after the caret
You need this jquery plugin for caret manipulation: http://jcaret.googlecode.com/
<input id="myTextArea" value="a*(b*(c+d))">
</input>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://jcaret.googlecode.com/files/jquery.caret.1.02.min.js"></script>
<script type="text/javascript">
var old_value = $('#myTextArea').val();
function filterString(a) {
return a.replace(/[^\(\)]/g,"");
}
$('#myTextArea').keyup(function(){
var end_of_insertion = $(this).caret().start;
var new_value = $(this).val();
var i=0;
while(i<old_value.length && i<new_value.length && old_value[i]==new_value[i]) {
i++;
}
if(i>=end_of_insertion)return;
// i now points to first different character in strings old_value and new_value
new_value = new_value.substr(0,i)
+ filterString(new_value.substr(i,end_of_insertion-i))
+ new_value.substr(end_of_insertion);
$('#myTextArea').val(new_value).caret({start: end_of_insertion, end: end_of_insertion});
old_value = new_value;
});
</script>
Upvotes: 1