Using JavaScript how do you to detect what text the user pastes into a textarea?
You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?
function getTextAreaSelection(textarea) {
var start = textarea.selectionStart, end = textarea.selectionEnd;
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}
function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end)
});
}, 1);
};
}
var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
alert(pasteInfo.text);
// pasteInfo also has properties for the start and end character
// index and length of the pasted text
});
HTML5 already provides onpaste not only <input/> , but also editable elements (<p contenteditable="true" />, ...)
<input type="text" onpaste="myFunction()" value="Paste something in here">
More info here
Quite an old thread, but you might now use https://willemmulder.github.io/FilteredPaste.js/ instead. It will let you control what gets pasted into a textarea or contenteditable.
Works on IE 8 - 10
Creating custom code to enable the Paste command requires several steps.
Set the event object returnValue to false in the onbeforepaste event to enable the Paste shortcut menu item.
Cancel the default behavior of the client by setting the event object returnValue to false in the onpaste event handler. This applies only to objects, such as the text box, that have a default behavior defined for them.
Specify a data format in which to paste the selection through the getData method of the clipboardData object.
invoke the method in the onpaste event to execute custom paste code.
To invoke this event, do one of the following:
Right-click to display the shortcut menu and select Paste.
Or press CTRL+V.
Examples
<HEAD>
<SCRIPT>
var sNewString = "new content associated with this object";
var sSave = "";
// Selects the text that is to be cut.
function fnLoad() {
var r = document.body.createTextRange();
r.findText(oSource.innerText);
r.select();
}
// Stores the text of the SPAN in a variable that is set
// to an empty string in the variable declaration above.
function fnBeforeCut() {
sSave = oSource.innerText;
event.returnValue = false;
}
// Associates the variable sNewString with the text being cut.
function fnCut() {
window.clipboardData.setData("Text", sNewString);
}
function fnBeforePaste() {
event.returnValue = false;
}
// The second parameter set in getData causes sNewString
// to be pasted into the text input. Passing no second
// parameter causes the SPAN text to be pasted instead.
function fnPaste() {
event.returnValue = false;
oTarget.value = window.clipboardData.getData("Text", sNewString);
}
</SCRIPT>
</HEAD>
<BODY onload="fnLoad()">
<SPAN ID="oSource"
onbeforecut="fnBeforeCut()"
oncut="fnCut()">Cut this Text</SPAN>
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here"
onbeforepaste="fnBeforePaste()"
onpaste="fnPaste()">
</BODY>
Full doc: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx
I like the suggestion for the right click
$("#message").on('keyup contextmenu input', function(event) {
alert("ok");
});
finded here:
Source:
Fire event with right mouse click and Paste
Following may help you
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == //event code of ctrl-v)
{
//some code here
}
}
<teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea>
The input event fires when the value of an , , or element has been changed.
const element = document.getElementById("input_element_id");
element.addEventListener('input', e => {
// insertText or insertFromPaste
if(inputType === "insertFromPaste"){
console.log("This text is copied");
}
if(inputType === "insertText"){
console.log("This text is typed");
}
})
You could either use html5 oninput attribute or jquery input event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$("body").on('input','#myinp',function(){
$("span").css("display", "inline").fadeOut(2000);
});
</script>
<style>
span {
display: none;
}
</style>
</head>
<body>
<input id="myinp" type="search" onclick="this.select()" autocomplete="off" placeholder="paste here">
<span>Nice to meet you!</span>
</body>
</html>
Related
Edited:
I forgot to add a 'native' (for JS or browser) word to questions, as browsers (or JS i'm not sure) have a undo/redo feature in inputs, but it don't work with programmatically edited input and my main question is, if it is possible to add a code to trigger that native callback to previous value feature.
I tried to do this with document.execCommand paste/insertText but it didn't work and is marked as obsolete.
Old:
I have a custom action on keypress in input, for example where number have changed sign(+-) when '-' button is pressed.
I want to add that action to native undo/redo (ctrl+z/y) history stack, with preventing others default actions triggered when button responsible for my action is clicked.
Is this possible?
If no, to remove current, native undo/redo input feature, using event.preventDefault in crtl+z/y click detection would be enough? To replace it by custom undo/redo.
Is this dependable on browser?
I experimented with code on Firefox and Edge.
Is there something like History API for input available for JS and where i can read about it and how it is named in code?
As for similar topics in stack are old and i tried them but they didn't work (or i used them in wrong way).
$(document).ready(function() {
$(":input").on('keypress', function(e) {
//On minus button click, reverse sign for number in input:
if (e.key === '-') {
e.preventDefault();
//TODO: Add this change in input to undo/redo changes history:
$(this).val(-$(this).val());
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Number: <input type="text" name="num"><br>
</body>
</html>
i3z slighty enchanted answer:
Ctrl+z instead of '-' button for Undo action.
Fixed bug with 2 clicks needed to use undo action after adding new element.
Sign change action from my question is added to code.
Added empty "" as default in history stack.
// Global Varaibles
// Edited: Added empty undo element, fixed undo working from 2nd click after adding new element to history.
var historyValues = [''];
var undoSteps = 2;
var maxSteps = 1;
var currentUndo = 1;
// Add event listener to track input and update historyValues
$(":input").on('input', function (evt) {
historyValues.push(this.value);
maxSteps = historyValues.length;
//console.log(historyValues);
// Check if 'Undo' been used if yes reset cause input been changed
if (undoSteps !== 2) {
undoSteps = 2;
}
});
$(document).ready(function() {
$(":input").on('keydown', function(e) {
if (undoSteps > maxSteps) {
// When you run out of backward steps, reset steps
undoSteps = 1;
}
// check for key (Edited: changed to z) and ensure 'currentUndo' not less than 0
if (e.ctrlKey && e.key === 'z' && currentUndo >= 0) {
e.preventDefault();
// tracking steps backward for every-time key '-' pressed
currentUndo = (maxSteps - undoSteps);
//console.log(maxSteps+' maxSteps - undoSteps '+undoSteps);
// Get previous value from history array
var newValue = historyValues[currentUndo];
//console.log(currentUndo+' current - value '+newValue);
$(this).val(newValue);
// Add +1 steps as we used undo once
undoSteps++;
}
});
$(":input").on('keypress', function(e) {
//Edited: Added custom action on key '-' press
if (e.key === '-') {
e.preventDefault();
$(this).val(-$(this).val());
//Trigger history
$(this).trigger('input');
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Number: <input type="text" name="num"><br>
</body>
</html>
Simple Undo JS Script
You'll be able to capture event of (⌘ + z) or (CTRL + z). Therefore, you'll be able to preform this Undo JS implementation to have history stack of values every-time input changes.
You should have Event Listener (input) either via DOM or jQuery e.g.
$(":input").on('input', function (evt) {
console.log(this.value)
}
Now, you can trace any changes in input been targeted using jQuery Selector.
You should also define global variables inside your document, where you can track following:
History Stack (historyValues)
Steps To Take (undoSteps)
Maximum Steps (maxSteps)
Current Step (currentUndo)
Source Code
// Global Varaibles (Controls)
var historyValues = [''];
var undoSteps = 2;
var maxSteps = 1;
var currentUndo = 1;
// Add event listener to track input changes and update historyValues
$(":input").on('input', function (evt) {
historyValues.push(this.value);
maxSteps = historyValues.length;
//console.log(historyValues);
// Check if 'Undo' been used if yes reset cause input been changed
if (undoSteps !== 2) {
undoSteps = 2;
}
});
$(document).ready(function() {
$(":input").on('keydown', function(e) {
if (undoSteps > maxSteps) {
// When you run out of backward steps, reset steps
undoSteps = 1;
}
// Edited: Supports (⌘ + z and CTRL + z)
if ( (e.ctrlKey && e.key === 'z') || (e.metaKey && e.key === 'z') ) {
e.preventDefault();
// Ensure 'currentUndo' not less than 0
if (currentUndo >= 0) {
// tracking steps backward
currentUndo = (maxSteps - undoSteps);
// Get previous value from history array
var newValue = historyValues[currentUndo];
$(this).val(newValue);
// Add +1 steps as we used undo once
undoSteps++;
}
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Number: <input type="text" name="num"><br>
</body>
</html>
I am handling the content inside a textarea using binding a function to the event "input propertychange"
Like this:
$('#textarea').bind('input propertychange', function () {
var textarea = document.getElementById('textarea');
window.lastLineWriting = textarea.value.substr(0, textarea.value.length).split("\n").length;
var writingOnLine = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
if (writingOnLine < window.lastLineWriting) {
//dont write on textarea
}
});
I don't know how to prevent the char typed by the user's keyboard to appear on the textarea... Inside that if I want to prevent the text to be inserted on textarea..
How can I do this?
you could easily stop the user from typing with this code, using jQuery:
$('textarea').bind('keypress', function (e) {
e.preventDefault();
return false;
});
NOTE:
this code will prevent the user from typing in all the textareas, to bind it specifically to one or some selected elements, you must change the selector to the desired elements.
var editable = false // Your Condition
if(editable != "true"){
$("#textarea" ).attr("disabled",true);
}
I'm can't figure out a way of displaying a message if a specific word is inputed into an input box. I'm basically trying to get javascript to display a message if a date, such as '01/07/2013', is inputed into the input box.
Here is my html
<p>Arrival Date</p> <input type="text" id="datepicker" id="food" name="arrival_date" >
I'm using a query data picker to select the date.
You can insert code in attribute onchange
onchange="if(this.value == 'someValue') alert('...');"
Or create new function
function change(element){
if(element.value == 'someValue'){
alert('...');
}
}
And add attribute
onchange="change(this);"
Or add event
var el = document.getElementById('input-id');
el.onchange = function(){
change(el); // if 'el' doesn't work, use 'this' instead
}
I'm not sure if it works, but it should :)
Use .val() to get the value of the input and compare it with a string
var str = $('#datapicker').val(), // jQuery
// str = document.getDocumentByI('datapicker').value ( vanilla js)
strToCompare = '01/07/2013';
if( str === strToCompare) {
// do something
}
And encase this in either change or any keyup event to invoke it..
$('#datepicker').change(function() {
// code goes here
});
Update
Try the code below.
$(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.on('change', function () {
var str = $datepicker.val(),
strToCompare = '07/19/2013';
if (str === strToCompare) {
console.log('Strings match')
}
else {
console.log('boom !!')
}
});
});
Check Fiddle
Your input has 2 ids. You need to remove id="food". Then the following should work with IE >= 9:
document.getElementById('datepicker').addEventListener(
'input',
function(event) {
if (event.target.value.match(/^\d+\/\d+\/\d+$/))
console.log("Hello");
}, false);
Is there a way to stop a webpage from refreshing completely when the enter button is pressed in a input text element?
I'm looking to create a search field that I can get the text from when enter is pressed to filter objects and only display the ones that contain text from the search field.
I've tried the following to try and catch the enter button but it does not work.
function setupSearchField() {
document.getElementById("searchField").onKeyDown = function(event) {
var holder;
if (window.event) {
holder = window.event.keyCode;
} else {
holder = event.which;
}
keyPressed(holder);
}
}
function keyPressed(key) {
if (key == 13) {
event.cancelBubble = true;
return false;
}
}
If the input element is inside a form, and that form is not actually being submitted to the server, remove the form.
The reason your code doesn't work is becaue the onkeydown event should be in lowercase, and you aren't actually returning something in it (try return keyPressed(holder); - or just move the keyPressed function's code into setupSearchField, since it seems kind of pointless to me to have it as a separate function).
This happens when there is only one text input, regardless of whether your button (if any) has type="submit" or not. It's documented here.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2
So, as suggested by other people earlier, you then have to simply stop this default behavior.
Is your search field inside a element ? Then hitting 'enter' fires a submit event to the form element.
In this case you could process your filtering by defining onsubmit on the form element.
<form id="searchForm">
<input type="text" name="search" />
</form>
<script>
document.getElementById('searchForm').onsubmit = function() {
var searchValue = this.search.value;
// process
return false;
}
</script>
Something like this maybe.
Just add the following javascript code to your Visualforce page:
<script type='text/javascript'>
function stopRKey(evt)
{
var evt=(evt) ? evt : ((event) ? event : null);
var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
I want to select all of the text inside of a textarea when a user clicks the textarea. I tried onclick="this.focus()", but this didn't do anything. I tried onclick="this.highlight()", but this caused an error. What should I do?
This may annoy your users since it prevents the useful default behaviour of placing the caret where the user clicked and I therefore recommend against it in general. That said, the solution for most browsers is onclick="this.select()".
However, this will not work in Chrome [UPDATE February 2014: it does now seem to work in recent versions of Chrome]. For a workaround and general background on this issue, see the following question: jQuery - select all text from a textarea
onclick="this.focus();this.select()" readonly="readonly"
<script type="text/javascript">
function SelectAll(id)
{
document.getElementById(id).focus();
document.getElementById(id).select();
}
</script>
Textarea:<br>
<textarea rows="3" id="txtarea" onClick="SelectAll('txtarea');" style="width:200px" >This text you can select all by clicking here </textarea>
I got this code here
onclick="this.focus()" is redundant, as the focus() method is the same as clicking in the textarea (but it places the cursor at the end of the text).
highlight() isn't even a function, unless of course you created it somewhere else.
Conclusion: do this.select()
Seem to more browsers supporting setSelectionRange() than select()
1 way: - Use setSelectionRange()
https://caniuse.com/#search=setSelectionRange
const my_textarea = document.getElementById("my_textarea");
document.getElementById("my_but").onclick = function () {
if(my_textarea.value !== ""){
my_textarea.onfocus = function () {
my_textarea.setSelectionRange(0, my_textarea.value.length);
my_textarea.onfocus = undefined;
}
my_textarea.focus();
}
}
<textarea id="my_textarea" name="text">1234567</textarea>
<br>
<button id="my_but">Select</button>
2 way: - Use select()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select#browser_compatibility
const my_textarea = document.getElementById("my_textarea");
document.getElementById("my_but").onclick = function () {
if(my_textarea.value !== ""){
my_textarea.onfocus = function () {
my_textarea.select();
my_textarea.onfocus = undefined;
}
my_textarea.focus();
}
}
<textarea id="my_textarea" name="text">1234567</textarea>
<br>
<button id="my_but">Select</button>
You have to use the .focus() as well as the .select() Javascript function to achieve the desired result.
Check the link below for an example:
http://www.plus2net.com/javascript_tutorial/textarea-onclick.php
To complete other answers perhaps you would like to copy the code/text you've just clicked, so use:
onclick="this.focus();this.select();document.execCommand('copy')"
const elem = document.elementFromPoint(clientX, clientY)
if (elem.select) { // Make sure the method exists.
elem.focus()
elem.select()
}
You may not want to spend time finding your object.
For example, you have written extensions to inject scripts into the web page.
At this time, you do not need to consider the element ID that you can apply immediately.
Example
<textarea rows="3" style="width:200px">"Double click" or Press "F4" to select all text</textarea>
<script>
let clientX, clientY
document.addEventListener("mousemove", (e) => {
clientX = e.clientX
clientY = e.clientY
})
selectAllFunc = () => {
const elem = document.elementFromPoint(clientX, clientY)
if (elem.select) { // Make sure the method exists.
elem.focus()
elem.select()
}
}
document.addEventListener("keydown", (keyboardEvent) => {
if (keyboardEvent.key === "F4") { // && keyboardEvent.ctrlKey
selectAllFunc()
}
})
document.addEventListener("dblclick", (e) => {
selectAllFunc()
})
</script>