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>
Related
I want to execute a function when any of the text field is focused.
Something like this, BUT purely in Javascript - NOT IN JQUERY
$("input").focus(function() {
alert("Hello World");
});
I am trying:
document.getElementById("text1").onfocus = alert(1);
But this only shows the alert after loading page, nothing else.
Thanks
Get elements by tag name & loop("Iterate") on them for attaching focus.
http://www.w3schools.com/jsref/met_doc_getelementsbytagname.asp
var x=document.getElementsByTagName("input");
EDIT : Put this at the end of page
<script>
var x=document.getElementsByTagName("input");
for(i=0;i<x.length;i++)
{
x[i].addEventListener('focus',function(){
alert("focus");
});
}
</script>
Yet another way with document.querySelectorAll for new browser
var inputs = document.querySelectorAll('input');
and then in loop for example use addEventListener
for(var i=0,len=inputs.length;i<len;i++){
inputs[i].addEventListener('focus',function(){
//handle event
})
}
If you like some aspects of jQuery, but do not want to include the entire library in your project, you can check out You Might Not Need jQuery. You can set the minimum version of IE that you support, in the settings at the top of the page.
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function(){
handler.call(el);
});
}
}
function addEventListeners(selector, type, handler) {
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++) {
addEventListener(elements[i], type, handler);
}
}
addEventListeners('input', 'focus', function(e) {
if (this.value !== this.placeholder) {
this.value = this.placeholder;
} else {
this.value = '';
}
});
input {
display: block;
}
<input type="text" placeholder="One" />
<input type="text" placeholder="Two" />
<input type="text" placeholder="Three" />
I know I am probably late to this, but I just wanted to add my 2 cents, as I see a lot of Stackoverflow answers like this still using JQuery and many people have moved on from JQuery, and might want another option
You could either use the focusin event or capture the focus in the Capturing phase from the top down, in either JQuery or JS, If It works in JS, it should work in the other, as I dont use JQ
let form = document.forms.myForm;
form.addEventListener('focus', (event) => {
console.log('Focused!');
console.log(event.target);
}, true);
//Work around focusin
form.addEventListener('focusin', (event) => {
console.log('Focused In!');
console.log(event.target);
});
This one supports input elements that are loaded asynchronously too.
document.addEventListener("focusin", inputBoxListener)
function inputBoxListener(event) {
if (event.target.tagName === "INPUT") {
console.log("focused on input")
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/focusin_event
I am trying to do something really simple using only Javascript (not JQuery).
Basically, I want to use a checkbox to toggle the text in a textarea. So if the checkbox is unchecked I want it to say "Hello" in the textarea. If the checkbox is checked, the textarea should say "Goodbye".
I'm just getting started with Javascript, so any help would be appreciated.
Thanks
Here is the code:
var myswitch = document.getElementsByTagName("myonoffswitch");
var mytextarea= document.getElementsByTagName("mytextarea");
myswitch.onchange = function(){
if(this.checked){
mytextarea.value = "Hello"
}else{
mytextarea.value = "Goodbye"
}
}
If your controls are in a form, you can do something really simple like:
<form>
<textarea name="ta"></textarea>
<input type="checkbox" onclick="
this.form.ta.value = this.checked? 'Hello':'Goodbye';
">
</form>
Note that using the change event with a checkbox means that in some browsers, the event won't be dispatched until the checkbox loses focus, so better to use the click event.
You should be using document.getElementById instead of getElementsByTagName
I can't tell from your code snippet if you've wrapped your code in an onload function. This is required in situations where your DOM elements are not loaded in the HTML at the time your javascript is running
Here's an example
window.onload = function () {
var myswitch = document.getElementById("myonoffswitch");
var mytextarea = document.getElementById("mytextarea");
myswitch.onchange = function () {
if (this.checked) {
mytextarea.value = "Hello";
} else {
mytextarea.value = "Goodbye";
}
}
//code here
}
And a fiddle is available here: http://jsfiddle.net/C4jVG/
I've tried something. This should work for you
HTML
<input type="checkbox" id="myonoffswitch">Switch</input>
<textarea id="mytextarea" cols="30" rows="10"></textarea>
Javascript
function fillText() {
var myswitch = document.getElementById("myonoffswitch");
var mytextarea= document.getElementById("mytextarea");
myswitch.onchange = function(){
if(this.checked){
mytextarea.value = "Hello"
}else{
mytextarea.value = "Goodbye"
}
}
}
window.onload = fillText;
Just try replacing getElementsByTagName in your code with getElementById this will solve your problem.
Much like when typing a comment on Facebook and you hit #username, it reacts to that, letting you choose a username inline.
Using jQuery, how would one go about hooking up an event listener for [text:1]. I want an event to fire when the user has entered [text: into a text field.
Zurb created a textchange plugin that will help. See their "Validate Text" example towards the bottom, i believe its almost exactly what you're looking for..
http://www.zurb.com/playground/jquery-text-change-custom-event
use keyup function to trigger. Split all the string and check it.
[UPDATE]: More Improved Version
<script>
var totalcount=0;
$(function (){
$('#text').keyup(
function (){
var arr = $(this).val().split(" ");
var matchitems = count('hello', arr);
//console.log(matchitems);
if(matchitems > totalcount){
alert('hello');
totalcount = matchitems;
}
if(matchitems < totalcount)
{
totalcount = matchitems;
}
}
)
})
function count(value, array)
{
var j=0;
for(var i=0;i<array.length;i++)
{
if(array[i] == "hello"){
j++;
}
}
return j;
}
</script>
<input type="text" id="text" />
})
</script>
<input type="text" id="text" />
Using keyup like #experimentX mentioned is the way you want to go b/c then you'll know that your user has inputed value then. However, running a for loop would be extremely costly on every single keyup event. Instead, since you know the value you want already, you can use a preset regexp to search for your value:
<input type="text" id="text" value="" />
<script>
$(function () {
var $input = $('#text');
$input.keyup(function (e) {
var regexp = /\[text\:/i,
val = $(this).val();
if (regexp.test(val)) {
console.log('i have it: ', val);
}
});
});
</script>
Here are a couple additional scenarios on how you can write the actual regexp.
You want the string to be at the very beginning of the input: var regexp = /^\[text\:/i;
Building on the one above, but incorporate any amount of whitespace in front of the text you actually want: var regexp = /^\s+?\[text\:/i;
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>
Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed