Reputation: 69
I am trying to remove the whole word while pressing backspace in a text area,while pressing backspace it should check the current word along with one more word contains @, if this matching found while removing it should remove the word else it should remove the letters like what default backspace does.
In my example while removing the text using backspace it should remove the words user and @test in a single key press
Here is my example:
<textarea id="editabletxt">Hello @test user how are you</textarea>
$('#editabletxt').keyup(function (e) {
if (e.keyCode == 8) {
e.preventDefault();
var text = $(this).val().split(' ');
text.splice(text.length-1);
$(this).val(text.join(' '));
}
})
Fiddle: http://jsfiddle.net/n7ZWc/
Upvotes: 2
Views: 3337
Reputation: 949
We needed a similar functionality and came up with the following solution,
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
var posEnd = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
return [pos, posEnd];
};
$.fn.setCursorPosition = function(start, end) {
$(this).prop("selectionStart", start);
$(this).prop("selectionEnd", end);
}
$('#text').keydown(function (e) {
var position = $(this).getCursorPosition();
var deleted = '';
var val = $(this).val();
if (e.which != 8) {
return true;
}
if (position[0] != position[1]) {
return true;
}
if (position[0] <= 0) {
return true;
}
let charToDelete = val.substr(position[0] - 1, 1);
if ( charToDelete == " " ) {
return true;
}
let nextChar = val.substr(position[0], 1);
if ( nextChar == " " || nextChar == "" ) {
start = position[0];
end = position[0];
while(val.substr(start - 1, 1) != " " && start - 1 >= 0) {
start -= 1;
}
e.preventDefault();
$(this).setCursorPosition(start, end);
//let newString = val.slice(0, start) + val.slice(end, val.length);
//$(this).val(newString);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text">Hello @test user how are you</textarea><br />
Upvotes: 3