Caret positition / Selection inside DIV, Textbox, Textarea, etc - javascript

Is there a total solution for getting a caret position and/or selection inside every browser from different elements. I'm looking for a solution witch I can execute like
mGetCaretPosition(iControl) witch will return the caret position inside it`s element.
I have tried a lot of functions:
selection (window/document) [document=IE, window=Opera]
getSelection (window/document) [document=Firefox, document=Chrome, document=Safari]
selectionStart (input/textarea) [All]
craeteRange (selection)
createTextRange (selection)
Calling a method like document.selection.createRange().text doesn't return a caret position because it doesn't have a selection. When setting tRange.moveStart('character', -X) the X isn't a known value. When you use this inside a div and the caret is in the middle it takes the code before the div.

I have build this today. It`s a combination of youre response alex and al the other results inside google. I have tested it inside the browsers IE9, Chrome, Opera, Safari and Firefox on the PC and also on a HTC Sensation with Android with the default browser, Firefox, Chrome and Opera.
Only the Opera on the mobile device did have some troubles.
My solution:
// Control
var BSControl = function(iControl)
{
// Variable
var tControl = (typeof iControl == 'string' ? document.getElementById(iControl) : iControl);
// Get Caret
this.mGetCaret = function()
{
// Resultaat aanmaken
var tResult = -1;
// SelectionStart
// *) Input & Textarea
if(tResult == -1 && (tControl.selectionStart || tControl.selectionStart == '0'))
{
tResult = tControl.selectionStart;
}
// ContentWindow.GetSelection
// *) IFrame
if(tResult == -1 && (tControl.contentWindow && tControl.contentWindow.getSelection))
{
var tRange= tControl.contentWindow.getSelection().getRangeAt(0);
tResult = tRange.startOffset;
}
// GetSelection
// *) Div
if(tResult == -1 && (window.getSelection))
{
var tRange= window.getSelection().getRangeAt(0);
tResult = tRange.startOffset;
}
// Resultaat teruggeven
return tResult;
}
// Set Caret
this.mSetCaret = function(iPosition)
{
// SelectionStart
// *) Input & Textarea
if(tControl.selectionStart || tControl.selectionStart == '0')
{
tControl.selectionStart = iPosition;
tControl.selectionEnd = iPosition;
return;
}
// ContentWindow.GetSelection
// *) IFrame
if(tControl.contentWindow && tControl.contentWindow.getSelection)
{
var tRange = tControl.contentDocument.createRange();
tRange.setStart(tControl.contentDocument.body.firstChild, iPosition);
tRange.setEnd(tControl.contentDocument.body.firstChild, iPosition);
var tSelection = tControl.contentWindow.getSelection();
tSelection.removeAllRanges();
tSelection.addRange(tRange);
return;
}
// GetSelection
// *) Div
if(window.getSelection)
{
var tSelection = window.getSelection();
var tRange= tSelection.getRangeAt(0);
tRange.setStart(tControl.firstChild, iPosition);
tRange.setEnd(tControl.firstChild, iPosition);
tSelection.removeAllRanges();
tSelection.addRange(tRange);
return;
}
}
// Get Selection
this.mGetSelection = function()
{
// Resultaat aanmaken
var tResult = null;
// SelectionStart
// *) Input & Textarea
if(tResult == null && (tControl.selectionStart || tControl.selectionStart == '0'))
{
tResult = this.mGet().substring(tControl.selectionStart, tControl.selectionEnd);
}
// ContentWindow.GetSelection
// *) IFrame
if(tResult == null && (tControl.contentWindow && tControl.contentWindow.getSelection))
{
var tSelection = tControl.contentWindow.getSelection()
tResult = tSelection.toString();
}
// GetSelection
// *) Div
if(tResult == null && (window.getSelection))
{
var tSelection = window.getSelection()
tResult = tSelection.toString();
}
// Resultaat teruggeven
return tResult;
}
// Set Selection
this.mSetSelection = function(iFrom, iUntil)
{
// SelectionStart
// *) Input & Textarea
if(tControl.selectionStart || tControl.selectionStart == '0')
{
tControl.selectionStart = iFrom;
tControl.selectionEnd = iUntil;
return;
}
// ContentWindow.GetSelection
// *) IFrame
if(tControl.contentWindow && tControl.contentWindow.getSelection)
{
var tRange = tControl.contentDocument.createRange();
tRange.setStart(tControl.contentDocument.body.firstChild, iFrom);
tRange.setEnd(tControl.contentDocument.body.firstChild, iUntil);
var tSelection = tControl.contentWindow.getSelection();
tSelection.removeAllRanges();
tSelection.addRange(tRange);
return;
}
// GetSelection
// *) Div
if(window.getSelection)
{
var tSelection = window.getSelection();
var tRange= tSelection.getRangeAt(0);
tRange.setStart(tControl.firstChild, iFrom);
tRange.setEnd(tControl.firstChild, iUntil);
tSelection.removeAllRanges();
tSelection.addRange(tRange);
return;
}
}
// Set
this.mSet = function(iValue)
{
// Afhankelijk van aanwezige property waarde instellen
if('value' in tControl)
{
tControl.value = iValue;
}else if('innerText' in tControl)
{
tControl.innerText = iValue;
}else if('textContent' in tControl)
{
tControl.textContent = iValue;
}else if('innerHTML' in tControl)
{
tControl.innerHTML = iValue;
}
}
// Get
this.mGet = function()
{
// Resultaat aanmaken
var tResult = null;
// Afhankelijk van aanwezige property waarde instellen
if('value' in tControl)
{
tResult = tControl.value;
}else if('innerText' in tControl)
{
tResult = tControl.innerText;
}else if('textContent' in tControl)
{
tResult = tControl.textContent;
}else if('innerHTML' in tControl)
{
tResult = tControl.innerHTML;
}
// Resultaat teruggeven
return tResult;
}
}

Related

Insert "/" in MM/YYYY textbox on keypress event

I want to enter a "/" when user enters MM(2 digit) so it will be like MM/YYYY.
I have done similar for credit card number input which insert a space after 4 digit on keypress.
let ccNumber = e.target.value.split(" ").join("");
if (ccNumber.length > 0) {
ccNumber = ccNumber.match(new RegExp('.{1,4}', 'g')).join(" ");
}
e.target.value = ccNumber;
Fiddle
This works with
Regular keyboard input
Copy/Cut/Paste
Selected text
Adding the /
Because you're programmatically adding the / character, you have to update the cursor position whenever that affects the new input value. This can be more than one character if the user is pasting something. Most of the code complexity revolves around this issue.
There are a lot of comments in the code explaining the various situations that come up because of the /.
Full Code
var date = document.getElementById('date');
date.addEventListener('keypress', updateInput);
date.addEventListener('change', updateInput);
date.addEventListener('paste', updateInput);
date.addEventListener('keydown', removeText);
date.addEventListener('cut', removeText);
function updateInput(event) {
event.preventDefault();
var string = getString(event);
var selectionStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var selectionLength = selectionEnd - selectionStart;
var sanitizedString = string.replace(/[^0-9]+/g, '');
// Do nothing if nothing is added after sanitization
if (sanitizedString.length === 0) {
return;
}
// Only paste numbers that will fit
var valLength = date.value.replace(/[^0-9]+/g, '').length;
var availableSpace = 6 - valLength + selectionLength;
// If `/` is selected it should not count as available space
if (selectionStart <= 2 && selectionEnd >= 3) {
availableSpace -= 1;
}
// Remove numbers that don't fit
if (sanitizedString.length > availableSpace) {
sanitizedString = sanitizedString.substring(0, availableSpace);
}
var newCursorPosition = selectionEnd + sanitizedString.length - selectionLength;
// Add one to cursor position if a `/` gets inserted
if (selectionStart <= 2 && newCursorPosition >= 2) {
newCursorPosition += 1;
}
// Previous input value before current cursor position
var valueStart = date.value.substring(0, this.selectionStart);
// Previous input value after current cursor position
var valueEnd = date.value.substring(this.selectionEnd, date.value.length);
var proposedValue = valueStart + sanitizedString + valueEnd;
// Remove anything that's not a number
var sanitized = proposedValue.replace(/[^0-9]+/g, '');
format(sanitized);
this.setSelectionRange(newCursorPosition, newCursorPosition);
}
function removeText(event) {
if (event.key === 'Backspace' || event.type === 'cut') {
event.preventDefault();
var selectionStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var selectionLength = selectionEnd - selectionStart;
// If pressing backspace with no selected text
if (selectionLength === 0 && event.type !== 'cut') {
selectionStart -= 1;
// Remove number from before `/` if attempting to delete `/`
if (selectionStart === 2) {
selectionStart -= 1;
}
}
var valueStart = date.value.substring(0, selectionStart);
var valueEnd = date.value.substring(selectionEnd, date.value.length);
// Account for added `/`
if (selectionStart === 2) {
selectionStart += 1;
}
var proposedValue = valueStart + valueEnd;
var sanitized = proposedValue.replace(/[^0-9]+/g, '');
format(sanitized);
this.setSelectionRange(selectionStart, selectionStart);
}
}
function getString(event) {
if (event.type === 'paste') {
var clipboardData = event.clipboardData || window.clipboardData;
return clipboardData.getData('Text');
} else {
return String.fromCharCode(event.which);
}
}
function format(sanitized) {
var newValue;
var month = sanitized.substring(0, 2);
if (sanitized.length < 2) {
newValue = month;
} else {
var year = sanitized.substring(2, 6);
newValue = month + '/' + year;
}
date.value = newValue;
}
<input id="date" type="text" maxlength="7">
Try:
var date = document.getElementById('date');
date.addEventListener('keypress', function (event) {
var char = String.fromCharCode(event.which),
offset = date.selectionStart;
console.log(offset)
if (/\d/.test(char) && offset < 7) {
if (offset === 2) {
offset += 1;
}
date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1);
date.selectionStart = date.selectionEnd = offset + 1;
}
if (!event.keyCode) {
event.preventDefault();
}
});
<input id="date" type="text" value="mm/yyyy" maxlength="6" size="6">
function keypress(elem) { // get Input
if (typeof elem == 'string') {
if (document.getElementById(elem)) elem = document.getElementById(elem);
if (typeof elem == 'string') elem = document.getElementsByName(elem).item(0);
}
const el = elem; //handle error if not found input
el.maxLength = 19;
el.addEventListener('keypress', function (e) {
const t = e.keyCode || e.which
if (t == 8 || (t > 47 && t < 58)) { // limit numeric characters and backspace
if (t != 8) {
if (el.value.length == 2) el.value += '/';
if (el.value.length == 5) el.value += '/';
if (el.value.length == 10) el.value += ' ';
if (el.value.length == 13) el.value += ':';
if (el.value.length == 16) el.value += ':';
}
} else {
e.preventDefault();
}
});}

Convert first letter to uppercase on input box

JS Bin demo
This regex transform each lower case word to upper case. I have a full name input field. I do want the user to see that each word's first letter he/she pressed is converted to uppercase in the input field.
I have no idea how to properly replace the selected characters in the current input field.
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
// I want this value to be in the input field.
console.log(val);
});
Given i.e: const str = "hello world" to become Hello world
const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);
or:
const firstUpper = str.charAt(0).toUpperCase() + str.substr(1);
or:
const firstUpper = str[0] + str.substr(1);
input {
text-transform: capitalize;
}
http://jsfiddle.net/yuMZq/1/
Using text-transform would be better.
You can convert the first letter to Uppercase and still avoid the annoying problem of the cursor jumping to the beginning of the line, by checking the caret position and resetting the caret position. I do this on a form by defining a few functions, one for all Uppercase, one for Proper Case, one for only Initial Uppercase... Then two functions for the Caret Position, one that gets and one that sets:
function ProperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g,
function($1) { return $1.toUpperCase(); });
$(el).val(s);
setCaretPosition(el,pos.start);
}
function UpperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toUpperCase();
$(el).val(s);
setCaretPosition(el,pos.start);
}
function initialCap(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.substr(0, 1).toUpperCase() + s.substr(1);
$(el).val(s);
setCaretPosition(el,pos.start);
}
/* GETS CARET POSITION */
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {
el.value = el.value;
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
Then on document ready I apply a keyup event listener to the fields I want to be checked, but I only listen for keys that can actually modify the content of the field (I skip "Shift" key for example...), and if user hits "Esc" I restore the original value of the field...
$('.updatablefield', $('#myform')).keyup(function(e) {
myfield=this.id;
myfieldname=this.name;
el = document.getElementById(myfield);
// or the jquery way:
// el = $(this)[0];
if (e.keyCode == 27) { // if esc character is pressed
$('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end if (e.keyCode == 27)
// if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end else = if any other character is pressed //
}); // end $(document).keyup(function(e)
You can see a working fiddle of this example here: http://jsfiddle.net/ZSDXA/
Simply put:
$this.val(val);
$(document).ready(function() {
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
console.log(val);
$this.val(val);
});
});
As #roXon has shown though, this can be simplified:
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});
An alternative, and better solution in my opinion, would be to only style the element as being capitalized, and then do your logic server side.
This removes the overhead of any javascript, and ensures the logic is handled server side (which it should be anyway!)
$('input').on('keyup', function(event) {
$(this).val(function(i, v){
return v.replace(/[a-zA-Z]/, function(c){
return c.toUpperCase();
})
})
});
http://jsfiddle.net/AbxVx/
This will do for every textfield call function on keyup
where id is id of your textfield and value is value you type in textfield
function capitalizeFirstLetter(value,id)
{
if(value.length>0){
var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
document.getElementById(id).value=str;
}
}
only use this This work for first name in capital char
style="text-transform:capitalize;
Like
<asp:TextBox ID="txtName" style="text-transform:capitalize;" runat="server" placeholder="Your Name" required=""></asp:TextBox>
$('.form-capitalize').keyup(function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
this.value = val;
// I want this value to be in the input field.
console.log(val);
});

Trigger alert function event for text area node in Firefox Javascript XUL

I want to trigger an alert if the user reached max number of characters in the text area.
Generally my plugin fill the user node values directly to my plugin text box. So, I want to generate an alert if the user reached var mymaxlength = 20;
var mymaxlength = 20;
if ( nodeName == "textarea" && node.value.length >= mymaxlength ) {
// call your popup / alert function
alert('hi, you have reached 20 characters');
}
I have tried the above code, it didn't work without any errors? In my full code, the general alert is working but the alert inside the loop is not working?
1. Is it a good way of triggering an alert in onKeypress : function (e)? or
2. Would it be possible to trigger an alert if the user node has filed 20 characters in the fillText : function (node)?
Please assist me!
This is the full code:
run : function () {
//alert(content.document.cookie);
//alert("-"+content.document.cookie+"-");
var cookieTest = content.document.cookie
var JSESSIONID = pdees.get_Cookie("JSESSIONID");
if(verifyConnection){
if(JSESSIONID && cookieTest){
//var result = verifyUserIdentity(JSESSIONID);
var head = content.document.getElementsByTagName("head")[0];
var body = content.document.body;
//var style = content.document.getElementById("pdees-style");
//var allLinks = content.document.getElementsByTagName("pdees");
var foundLinks = 0;
//extract text element from body
if(document.getElementById && document.createTreeWalker && typeof NodeFilter!="undefined"){
var tw=document.createTreeWalker(body,NodeFilter.SHOW_TEXT,null,false);
lookForpdees(tw);
}
addJScode();
idpdeesbutton=0;
}else{
alert("You should connect to the Application Environment to be authentified");
}
}else{
//var result = verifyUserIdentity(JSESSIONID);
var head = content.document.getElementsByTagName("head")[0];
var body = content.document.body;
//var style = content.document.getElementById("pdees-style");
//var allLinks = content.document.getElementsByTagName("pdees");
var foundLinks = 0;
//extract text element from body
if(document.getElementById && document.createTreeWalker && typeof NodeFilter!="undefined"){
var tw=document.createTreeWalker(body,NodeFilter.SHOW_TEXT,null,false);
lookForpdees(tw);
}
addJScode();
idpdeesbutton=0;
}
},
onKeypress : function (e) {
var mymaxlength = 20;
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//text area cache onKeyPress code
//alert('hi1');
if ( nodeName == "textarea" && node.value == "" && e.keyCode == 13 ) {
pdees.fillText(node);
return;
}
if ( nodeName == "textarea" && node.value.length >= mymaxlength ) {
// call your popup / alert function
alert('hi, you have reached 20 characters');
}
// this node is a WYSIWYG editor or an editable node?
if ( ( nodeName != "html" || node.ownerDocument.designMode != "on" ) && node.contentEditable != "true" )
return;
if ( node.textContent == "" && e.keyCode == 13 ) {
pdees.fillText(node);
return;
}
if (!node.tacacheOnSave) {
pdees.fillText(node);
}
},
onChange : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onChange : "+nodeName);
if ( nodeName != "textarea" )
return;
pdees.fillText(node);
},
onInput : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onInput : "+nodeName);
// Only for textarea node
if ( node.nodeName.toLowerCase() != "textarea" )
return;
if ( node.value == "" )
return;
pdees.fillText(node);
},
fillText : function (node) {
nodeSRC = node;
if ( node.nodeName.toLowerCase() == "textarea" )
{
//alert('hi');
userContent = node.value;
//alert(userContent);
}
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);}
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
emptyNodeSRC : function (node){
if ( node.nodeName.toLowerCase() == "textarea" ) {
node.value = "";
}
else if ( node.nodeName.toLowerCase() == "html" ) {
node.ownerDocument.body.innerHTML = "";
}
else // element.contentEditable == true
node.innerHTML = "";
},
};
}();
Finally, I have found my problem and I have succeed to trigger mu custom alert:
In this function fillText : function (node)where I can trigger an alert for the userContent. So I made a length and triggered an alert for it.
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);
var myTest = userContent.length;
if(userContent.length == 30)
{
alert('Hi, there!');
}
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
Note: For complete code please refer to my question.

How do I insert some text where the cursor is? [duplicate]

This question already has answers here:
Inserting a text where cursor is using Javascript/jquery
(13 answers)
Closed 7 years ago.
I'm upgrading some Javascript which works on IE. However, I'm having some problems.
Heres the IE code:
var range = document.getElementById('text').contentWindow.window
.document.getElementById('Content').createTextRange();
var textObj = document.getElementById('text').contentWindow.window
.document.getElementById('Content');
var textFieldValue = theSmile;
if (range && textObj.CursorPos) {
var CursorPos = textObj.CursorPos;
CursorPos.text = CursorPos.text.charAt(CursorPos.text.length - 1)
== ' ' ?' ' + textFieldValue : textFieldValue;
} else {
textObj.value = textFieldValue;
}
I've tried replacing CreateTextRange with CreateRange for non-IE browsers, but this doesn't help. With code like this:
var range;
var textObj;
var iframeEl = document.getElementById('text');
if (iframeEl.contentDocument) { // DOM
range = iframeEl.contentDocument.getElementById('Content').createRange;
textObj= iframeEl.contentDocument.getElementById('Content');
} else if (iframeEl.contentWindow) { // IE win
range = iframeEl.contentWindow.document.getElementById('Content')
.createTextRange;
textObj= iframeEl.contentWindow.document.getElementById('Content');
}
Here's a function to insert text at the cursor in a textarea or text input, which is what it seems you have. It works in all major browsers:
function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range, doc = el.ownerDocument;
if (typeof el.selectionStart == "number"
&& typeof el.selectionEnd == "number") {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (doc.selection != "undefined" && doc.selection.createRange) {
el.focus();
range = doc.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}
You can use it as follows:
var iframeWin = document.getElementById('text').contentWindow;
var textObj = iframeWin.document.getElementById('Content');
insertTextAtCursor(textObj, "foo");

Getting Deleted character

in in Input field, if the user presses Backspace or Delete key, is there a way to get the deleted character.
I need to check it against a RegExp.
Assuming the input box has an id 'input'. Here is how with least amount of code you can find out the last character from the input box.
document.getElementById("input").onkeydown = function(evt) {
const t = evt.target;
if (evt.keyCode === 8) { // for backspace key
console.log(t.value[t.selectionStart - 1]);
} else if (evt.keyCode === 46) { // for delete key
console.log(t.value[t.selectionStart]);
}
};
<input id="input" />
The following will work in all major browsers for text <input> elements. It shouldn't be used for <textarea> elements because the getInputSelection function doesn't account for line breaks correctly in IE. See this answer for a (longer) function that will do this.
function getInputSelection(input) {
var start = 0, end = 0;
input.focus();
if ( typeof input.selectionStart == "number" &&
typeof input.selectionEnd == "number") {
start = input.selectionStart;
end = input.selectionEnd;
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
if (range) {
var inputRange = input.createTextRange();
var workingRange = inputRange.duplicate();
var bookmark = range.getBookmark();
inputRange.moveToBookmark(bookmark);
workingRange.setEndPoint("EndToEnd", inputRange);
end = workingRange.text.length;
workingRange.setEndPoint("EndToStart", inputRange);
start = workingRange.text.length;
}
}
return {
start: start,
end: end,
length: end - start
};
}
document.getElementById("aTextBox").onkeydown = function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
var deleteKey = (keyCode == 46), backspaceKey = (keyCode == 8);
var sel, deletedText, val;
if (deleteKey || backspaceKey) {
val = this.value;
sel = getInputSelection(this);
if (sel.length) {
deletedText = val.slice(sel.start, sel.end);
} else {
deletedText = val.charAt(deleteKey ? sel.start : sel.start - 1);
}
alert("About to be deleted: " + deletedText);
}
};
No, there is no variable that stores the deleted char. Unless you have a history for Undo/Redo, but it would be difficult to get the information out of that component.
Easiest would be to compare the contents of the input field before and after delete/backspace have been pressed.
You could try something with the caret position:
function getCaretPosition(control){
var position = {};
if (control.selectionStart && control.selectionEnd){
position.start = control.selectionStart;
position.end = control.selectionEnd;
} else {
var range = document.selection.createRange();
position.start = (range.offsetLeft - 1) / 7;
position.end = position.start + (range.text.length);
}
position.length = position.end - position.start;
return position;
}
document.getElementById('test').​​​​onkeydown = function(e){
var selection = getCaretPosition(this);
var val = this.value;
if((e.keyCode==8 || e.keyCode==46) && selection.start!==selection.end){
alert(val.substr(selection.start, selection.length));
} else if(e.keyCode==8){
alert(val.substr(selection.start-1, 1));
} else if(e.keyCode==46){
alert(val.substr(selection.start, 1));
}
}​
Tested on Chrome 6. See jsFiddle for an example

Categories