Append input with defined text in textfield - javascript

What I'm trying to do is to append .com in textfield during user input. Textfield will be empty and .com will be shown during typing domain name. Here is my not working code:
HTML
Enter domain name: <input type="text" id="domain">
Javascript
$(document).ready(function(){
$("input").keypress(function(){
$("#domain").val(this.value + ".com");
});
});
Not working demo:
http://jsfiddle.net/UUzux/25/
Thanks in advance.

I thought this was a great question. For a sleek solution, you could use the following code taken from
Set keyboard caret position in html textbox
to manually set the caret position in the input field:
function setCaretPosition(elemId, caretPos) {
var el = document.getElementById(elemId);
el.value = el.value;
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
} else {
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
} else { // fail
el.focus();
return false;
}
}
}
}
And then you'd implement it as follows:
$("input").keyup(function () {
var val = $("#domain").val();
val = val.replace(/\..*/g, ''); // replace this with whatever regex you need to deny whatever input you want.
$("#domain").val(val + ".com");
var caretPos = val.length;
var elemId = "domain";
setCaretPosition(elemId, caretPos);
});
Which will take anything after any . character out of the string, replace it each time with '.com' (you can replace this regex to handle whatever you need), and then set the cursor position to right before the '.com'
JSFiddle Demo
Also, to enable editing in the middle of the string you'd have to get the caret position. There's a stackoverflow question here
Get cursor position (in characters) within a text Input field
With good examples. I modified one of the answers as follows:
getCaretPosition = function (elemId) {
var input = $('#' + elemId);
if (!input) return; // No (input) element found
if ('selectionStart' in input[0]) {
// Standard-compliant browsers
return input[0].selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
And then your jQuery would look like this:
$("input").keyup(function () {
var val = $("#domain").val();
var elemId = "domain";
var caretPos = getCaretPosition(elemId);
val = val.replace(/\..*/g, '');
$("#domain").val(val + (val ? ".com" : ""));
setCaretPosition(elemId, caretPos);
});
Updated Fiddle with that implementation.

maybe this would help you.
http://jsfiddle.net/naeemshaikh27/UUzux/35/
$(document).ready(function(){
var prevText;
$("input").keyup(function(e){
var str=$("input").val().replace(".com", "");
str=str+'.com'
$("#domain").val( str );
});
});
well here is the updated one: http://jsfiddle.net/naeemshaikh27/UUzux/39/
But still looks aweful without caret moved

You could try this
$(document).ready(function () {
$("input").keyup(function (e) {
var kcode;
if (!e){
var e = window.event;
}
if (e.keyCode){
kcode = e.keyCode;
}
else if (e.which){
kcode = e.which;
}
if (kcode == 8 || kcode == 46){
return false;
}
this.value = this.value.replace('.com', '');
$("#domain").val(this.value + ".com");
var curpos = this.createTextRange();
curpos.collapse(true);
curpos.moveEnd('character', this.value.length - 4);
curpos.select();
});
});
I had to borrow some code from Joel on this post regarding disabling the backspace and delete keys. Just as he states in his post be careful using e.keyCode because not all browsers use it, some use e.Which.
JsFiddle Demo
Update: link to full list of key codes.

Related

Implementing Hashtags using Jquery

What I want to do is basically is that whenever I write anything that starts with a #, the color of the tagged string should change to some other color, say blue, immediately. And when I press space to end the string, the color should change back to black. I tried a logic like this on a contenteditable div:
if (# is pressed)
hashtagging = true
append "<span>" to div
if (space is pressed and hashtagging is true)
hashtagging = false
append "</span>" to div
This is not working as expected.
Something like this should do:
$(function() {
var hashtags = false;
$(document).on('keydown', '#myInputField', function (e) {
arrow = {
hashtag: 51,
space: 32
};
var input_field = $(this);
switch (e.which) {
case arrow.hashtag:
input_field.val(input_field.val() + "<span class='highlight'>");
hashtags = true;
break;
case arrow.space:
if(hashtags) {
input_field.val(input_field.val() + "</span>");
hashtags = false;
}
break;
}
});
});
Now this code checks on keydown if the hashtag or space is pressed and adds a span with a class for styling to it. Reason for checking for keydown instead of keyup is to add the tags before the actual input is added to the textfield. I used a text-field as input, but modify it with whatever you need.
Here's a working example, done by incorporating the solution given by Sondre with the solution by Mr_Green (Set the caret position always to end in contenteditable div) to place the caret at the end.
http://jsfiddle.net/344m4/1/
var hashTagList = [];
function logHashList(){
hashTagList = [];
$('.highlight').each(function(){
hashTagList.push(this.innerHTML);
});
for(var i=0;i<hashTagList.length;i++){
alert(hashTagList[i]);
}
if(hashTagList.length==0){
alert('You have not typed any hashtags');
}
}
$(function() {
var hashtags = false;
$(document).on('keydown', '#example-one', function (e) {
arrow = {
hashtag: 51,
space: 32
};
var input_field = $(this);
switch (e.which) {
case arrow.hashtag:
e.preventDefault();
input_field.html(input_field.html() + "<span class='highlight'>#");
placeCaretAtEnd(this);
hashtags = true;
break;
case arrow.space:
if(hashtags) {
e.preventDefault();
input_field.html(input_field.html() + "</span> ");
placeCaretAtEnd(this);
hashtags = false;
}
break;
}
});
});
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}

Validate input value before it is shown to user

I have an html <input> and some pattern (e.g. -?\d*\.?\d* float-signed value).
I should prevent typing the not matched value.
I did it in next way
jQuery.fn.numeric = function (pattern)
{
var jqElement = $(this), prevValue;
jqElement.keydown(function()
{
prevValue = jqElement.val();
})
jqElement.keyup(function(e)
{
if (!pattern.test(jqElement.val()))
{
jqElement.val(prevValue);
e.preventDefault();
}
prevValue = ""
})
};
JSFiddle DEMO
But in this case, value is shown to user and then corrected to right value.
Is it way to vaidate value before it is shown to user?
I can use pattern attribute from html5
$("#validateMe").on('keydown', function() {
var charBeingTyped = String.fromCharCode(e.charCode || e.which); // get character being typed
var cursorPosition = $(this)[0].selectionStart; // get cursor position
// insert char being typed in our copy of the value of the input at the position of the cursor.
var inValue = $(this).value().substring(0, cursorPosition) + charBeingTyped + $(this).value().substring(cursorPosition, $(this).value().length);
if(inValue.match(/-?\d*\.?\d*/)) return true;
else return false;
});
How about this POJS, I'm using a cross-browser addEvent function instead of jquery and not using any regexs, but I believe it achieves what you are looking for. Pressing + or - changes the sign of the value.
HTML
<input id="test" type="text" />
Javascript
/*jslint maxerr: 50, indent: 4, browser: true */
(function () {
"use strict";
function addEvent(elem, event, fn) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(null, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return ret;
}
function attachHandler() {
window.event.target = window.event.srcElement;
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return ret;
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
function verify(e) {
var target = e.target, // shouldn't be needed: || e.srcElement;
value = target.value,
char = String.fromCharCode(e.keyCode || e.charCode);
if (value.charAt(0) === "-") {
if (char === "+") {
e.target.value = value.slice(1);
}
} else if (char === "-") {
e.target.value = char + value;
return false;
}
value += char;
return parseFloat(value) === +value;
}
addEvent("test", "keypress", verify);
}());
On jsfiddle
I think I used the correct values keyCode || charCode
but you may want to search and check. A summary of the correct ones are available here
You could use this code to find out what character is pressed. Validate that character and, if it validates, append it to the input field.
Try this code:
jQuery.fn.numeric = function (pattern)
{
$(this).keypress(function(e)
{
var sChar = String.fromCharCode(!e.charCode ? e.which : event.charCode);
e.preventDefault();
var sPrev = $(this).val();
if(!pattern.test(sChar)){
return false;
} else {
sPrev = sPrev + sChar;
}
$(this).val(sPrev);
});
};
$("#validateId").numeric(/^-?\d*\.?\d*$/);
jsfiddle.net/aBNtH/
UPDATE:
My example validates each charachter while typing. If you prefer to check the entire value of the input field instead, I would suggest to validate the value on an other Event, like Input blur().

Can getSelection() be applied to just a certain element (not the whole document)?

I was testing out the getSelection() method, and I wanted my program to get the selected text in a certain paragraph of text and display it in a div tag. I used the following code:
var txt = document.getSelection();
document.getElementById("display").innerHTML = "The text you have selected is: " + txt + ".";
However, I want the program to only get selections made in the paragraph itself, not in the entire document. I tried using document.getElementById("id").getSelection(); but it didn't work.
How can I make it so getSelection() only applies to a certain element?
Here's one approach, tested only in Chromium 19 (Which supports textContent, for Internet Explorer innerText would have to be used instead):
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
var b = document.getElementsByTagName('body')[0],
o = document.getElementById('output');
b.onmouseup = function(e){
var selText = getSelectedText(),
targetElem = e.target.tagName.toLowerCase();
if (selText && targetElem == 'p') {
o.textContent = 'You selected the text: "' + selText + '" from a ' + targetElem + ' element.';
}
};​
JS Fiddle demo.
getSelection() is only available as a method of window and document. If you want to get a Range representing just the portion of the user selection that lies within a particular node, here's a function to do that, using my Rangy library (the code to do without the library would be longer and is beyond my enthusiasm to write right now):
function getSelectedRangeWithin(el) {
var selectedRange = null;
var sel = rangy.getSelection();
var elRange = rangy.createRange();
elRange.selectNodeContents(el);
if (sel.rangeCount) {
selectedRange = sel.getRangeAt(0).intersection(elRange);
}
elRange.detach();
return selectedRange;
}
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
written in coffeescript:
getSelected = ->
if window.getSelection
return window.getSelection()
else if document.getSelection
return document.getSelection()
else
selection = document.selection and document.selection.createRange()
return selection.text if selection.text
return false
false
delicious javascript

How to insert text into the textarea at the current cursor position?

I would like to create a simple function that adds text into a text area at the user's cursor position. It needs to be a clean function. Just the basics. I can figure out the rest.
Use selectionStart/selectionEnd properties of the input element (works for <textarea> as well)
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
This snippet could help you with it in a few lines of jQuery 1.9+: http://jsfiddle.net/4MBUG/2/
$('input[type=button]').on('click', function() {
var cursorPos = $('#text').prop('selectionStart');
var v = $('#text').val();
var textBefore = v.substring(0, cursorPos);
var textAfter = v.substring(cursorPos, v.length);
$('#text').val(textBefore + $(this).val() + textAfter);
});
New answer:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText
I'm not sure about the browser support for this though.
Tested in Chrome 81.
function typeInTextarea(newText, el = document.activeElement) {
const [start, end] = [el.selectionStart, el.selectionEnd];
el.setRangeText(newText, start, end, 'select');
}
document.getElementById("input").onkeydown = e => {
if (e.key === "Enter") typeInTextarea("lol");
}
<input id="input" />
<br/><br/>
<div>Press Enter to insert "lol" at caret.</div>
<div>It'll replace a selection with the given text.</div>
Old answer:
A pure JS modification of Erik Pukinskis' answer:
function typeInTextarea(newText, el = document.activeElement) {
const start = el.selectionStart
const end = el.selectionEnd
const text = el.value
const before = text.substring(0, start)
const after = text.substring(end, text.length)
el.value = (before + newText + after)
el.selectionStart = el.selectionEnd = start + newText.length
el.focus()
}
document.getElementById("input").onkeydown = e => {
if (e.key === "Enter") typeInTextarea("lol");
}
<input id="input" />
<br/><br/>
<div>Press Enter to insert "lol" at caret.</div>
Tested in Chrome 47, 81, and Firefox 76.
If you want to change the value of the currently selected text while you're typing in the same field (for an autocomplete or similar effect), pass document.activeElement as the first parameter.
It's not the most elegant way to do this, but it's pretty simple.
Example usages:
typeInTextarea('hello');
typeInTextarea('haha', document.getElementById('some-id'));
For the sake of proper Javascript
HTMLTextAreaElement.prototype.insertAtCaret = function (text) {
text = text || '';
if (document.selection) {
// IE
this.focus();
var sel = document.selection.createRange();
sel.text = text;
} else if (this.selectionStart || this.selectionStart === 0) {
// Others
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
this.value = this.value.substring(0, startPos) +
text +
this.value.substring(endPos, this.value.length);
this.selectionStart = startPos + text.length;
this.selectionEnd = startPos + text.length;
} else {
this.value += text;
}
};
A simple solution that works on firefox, chrome, opera, safari and edge but probably won't work on old IE browsers.
var target = document.getElementById("mytextarea_id")
if (target.setRangeText) {
//if setRangeText function is supported by current browser
target.setRangeText(data)
} else {
target.focus()
document.execCommand('insertText', false /*no UI*/, data);
}
setRangeText function allow you to replace current selection with the provided text or if no selection then insert the text at cursor position. It's only supported by firefox as far as I know.
For other browsers there is "insertText" command which only affect the html element currently focused and has same behavior as setRangeText
Inspired partially by this article
I like simple javascript, and I usually have jQuery around. Here's what I came up with, based off mparkuk's:
function typeInTextarea(el, newText) {
var start = el.prop("selectionStart")
var end = el.prop("selectionEnd")
var text = el.val()
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.val(before + newText + after)
el[0].selectionStart = el[0].selectionEnd = start + newText.length
el.focus()
}
$("button").on("click", function() {
typeInTextarea($("textarea"), "some text")
return false
})
Here's a demo: http://codepen.io/erikpukinskis/pen/EjaaMY?editors=101
Rab's answer works great, but not for Microsoft Edge, so I added a small adaptation for Edge as well:
https://jsfiddle.net/et9borp4/
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
// Microsoft Edge
else if(window.navigator.userAgent.indexOf("Edge") > -1) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue
+ myField.value.substring(endPos, myField.value.length);
var pos = startPos + myValue.length;
myField.focus();
myField.setSelectionRange(pos, pos);
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
function insertAtCaret(text) {
const textarea = document.querySelector('textarea')
textarea.setRangeText(
text,
textarea.selectionStart,
textarea.selectionEnd,
'end'
)
}
setInterval(() => insertAtCaret('Hello'), 3000)
<textarea cols="60">Stack Overflow Stack Exchange Starbucks Coffee</textarea>
If the user does not touch the input after text is inserted, the 'input' event is never triggered, and the value attribute will not reflect the change. Therefore it is important to trigger the input event after programmatically inserting text. Focusing the field is not enough.
The following is a copy of Snorvarg's answer with an input trigger at the end:
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
// Microsoft Edge
else if(window.navigator.userAgent.indexOf("Edge") > -1) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue
+ myField.value.substring(endPos, myField.value.length);
var pos = startPos + myValue.length;
myField.focus();
myField.setSelectionRange(pos, pos);
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
triggerEvent(myField,'input');
}
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
Credit to plainjs.com for the triggerEvent function
More about the oninput event at w3schools.com
I discovered this while creating an emoji-picker for a chat. If the user just select a few emojis and hit the "send" button, the input field is never touched by the user. When checking the value attribute it was always empty, even though the inserted emoji unicodes was visible in the input field. Turns out that if the user does not touch the field the 'input' event never fired and the solution was to trigger it like this. It took quite a while to figure this one out... hope it will save someone some time.
The code below is a TypeScript adaptation of the package https://github.com/grassator/insert-text-at-cursor by Dmitriy Kubyshkin.
/**
* Inserts the given text at the cursor. If the element contains a selection, the selection
* will be replaced by the text.
*/
export function insertText(input: HTMLTextAreaElement | HTMLInputElement, text: string) {
// Most of the used APIs only work with the field selected
input.focus();
// IE 8-10
if ((document as any).selection) {
const ieRange = (document as any).selection.createRange();
ieRange.text = text;
// Move cursor after the inserted text
ieRange.collapse(false /* to the end */);
ieRange.select();
return;
}
// Webkit + Edge
const isSuccess = document.execCommand("insertText", false, text);
if (!isSuccess) {
const start = input.selectionStart;
const end = input.selectionEnd;
// Firefox (non-standard method)
if (typeof (input as any).setRangeText === "function") {
(input as any).setRangeText(text);
} else {
if (canManipulateViaTextNodes(input)) {
const textNode = document.createTextNode(text);
let node = input.firstChild;
// If textarea is empty, just insert the text
if (!node) {
input.appendChild(textNode);
} else {
// Otherwise we need to find a nodes for start and end
let offset = 0;
let startNode = null;
let endNode = null;
// To make a change we just need a Range, not a Selection
const range = document.createRange();
while (node && (startNode === null || endNode === null)) {
const nodeLength = node.nodeValue.length;
// if start of the selection falls into current node
if (start >= offset && start <= offset + nodeLength) {
range.setStart((startNode = node), start - offset);
}
// if end of the selection falls into current node
if (end >= offset && end <= offset + nodeLength) {
range.setEnd((endNode = node), end - offset);
}
offset += nodeLength;
node = node.nextSibling;
}
// If there is some text selected, remove it as we should replace it
if (start !== end) {
range.deleteContents();
}
// Finally insert a new node. The browser will automatically
// split start and end nodes into two if necessary
range.insertNode(textNode);
}
} else {
// For the text input the only way is to replace the whole value :(
const value = input.value;
input.value = value.slice(0, start) + text + value.slice(end);
}
}
// Correct the cursor position to be at the end of the insertion
input.setSelectionRange(start + text.length, start + text.length);
// Notify any possible listeners of the change
const e = document.createEvent("UIEvent");
e.initEvent("input", true, false);
input.dispatchEvent(e);
}
}
function canManipulateViaTextNodes(input: HTMLTextAreaElement | HTMLInputElement) {
if (input.nodeName !== "TEXTAREA") {
return false;
}
let browserSupportsTextareaTextNodes;
if (typeof browserSupportsTextareaTextNodes === "undefined") {
const textarea = document.createElement("textarea");
textarea.value = "1";
browserSupportsTextareaTextNodes = !!textarea.firstChild;
}
return browserSupportsTextareaTextNodes;
}
Posting modified function for own reference. This example inserts a selected item from <select> object and puts the caret between the tags:
//Inserts a choicebox selected element into target by id
function insertTag(choicebox,id) {
var ta=document.getElementById(id)
ta.focus()
var ss=ta.selectionStart
var se=ta.selectionEnd
ta.value=ta.value.substring(0,ss)+'<'+choicebox.value+'>'+'</'+choicebox.value+'>'+ta.value.substring(se,ta.value.length)
ta.setSelectionRange(ss+choicebox.value.length+2,ss+choicebox.value.length+2)
}
/**
* Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
*/
String.prototype.insertInside = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
$('textarea').bind("keydown keypress", function (event) {
var val = $(this).val();
var indexOf = $(this).prop('selectionStart');
if(event.which === 13) {
val = val.insertInside(indexOf, 0, "<br>\n");
$(this).val(val);
$(this).focus();
}
});
Extending on Adriano's answer, we may also take cursor end into consideration which will make the "replace text" work
$('input[type=button]').on('click', function() {
var cursorStart = $('#text').prop('selectionStart');
var cursorEnd = $('#text').prop('selectionEnd');
var v = $('#text').val();
var textBefore = v.substring(0,cursorStart);
var textAfter = v.substring(cursorEnd);
$('#text').val(textBefore + $(this).val() + textAfter);
});
Changed it to getElementById(myField):
function insertAtCursor(myField, myValue) {
// IE support
if (document.selection) {
document.getElementById(myField).focus();
sel = document.selection.createRange();
sel.text = myValue;
}
// MOZILLA and others
else if (document.getElementById(myField).selectionStart || document.getElementById(myField).selectionStart == '0') {
var startPos = document.getElementById(myField).selectionStart;
var endPos = document.getElementById(myField).selectionEnd;
document.getElementById(myField).value =
document.getElementById(myField).value.substring(0, startPos)
+ myValue
+ document.getElementById(myField).value.substring(endPos, document.getElementById(myField).value.length);
} else {
document.getElementById(myField).value += myValue;
}
}

JavaScript get word before cursor

Okay, I've been looking all over the web to find a solution but I couldn't find one, is there a way to get the word before the caret position in an editable div so a bit like:
This is some| demo texts
This should return the word "some"... I don't know if this is possible, I would be glad for any help, thanks :).
With using Caret Position finder method provided here this will do what you want.
function ReturnWord(text, caretPos) {
var index = text.indexOf(caretPos);
var preText = text.substring(0, caretPos);
if (preText.indexOf(" ") > 0) {
var words = preText.split(" ");
return words[words.length - 1]; //return last word
}
else {
return preText;
}
}
function AlertPrevWord() {
var text = document.getElementById("textArea");
var caretPos = GetCaretPosition(text)
var word = ReturnWord(text.value, caretPos);
if (word != null) {
alert(word);
}
}
function GetCaretPosition(ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
<input id="textArea" type="text" />
<br />
<input id="Submit" type="submit" value="Test" onclick="AlertPrevWord()" />
Here is also a jsfiddle.
Here is a rough method using the Selection and Range objects.
function getWord() {
var range = window.getSelection().getRangeAt(0);
if (range.collapsed) {
text = range.startContainer.textContent.substring(0, range.startOffset+1);
return text.split(/\b/g).pop();
}
return '';
}
You can see it in action here: http://jsfiddle.net/ggfFw/1/.
This will not work in IE. If you need IE support look at the Rangy library.
I had something like that https://stackoverflow.com/a/9960262/986160 yet at some point it wasn't getting a selection in my Chrome browser. Based on my other answer here: https://stackoverflow.com/a/26728677/986160 - I changed it accordingly to be:
function getLastWordBeforeCaret() {
const containerEl = document.getElementById('element-id');
let preceding = '';
let sel;
let range;
if (window.getSelection) {
sel = window.getSelection();
if (sel && sel.rangeCount > 0) {
range = sel.getRangeAt(0).cloneRange();
range.collapse(true);
range.setStart(containerEl, 0);
preceding = range.toString();
}
}
let queryMatch = preceding.match(/([^\s]+)$/i);
if (queryMatch) {
return queryMatch[1];
} else {
return '';
}
}

Categories

Resources