Robust Way of Selecting All Text in Textbox - javascript

I'm trying to have the content of the an HTML textbox be selected fully onFocus.
I know the simple solution of putting a onfocus="this.select()" on the component but this is not a good solution because if a user double clicks into the area the selection is lost and in browsers like chrome it is rarely working like it should and just reverts into input form.
I have searched on Google for a little while and can't find a good solution, most suggestions are of this simple solution.
What I would like it is that the selection inside the textbox not change once selected and if possible the user should not be able to edit the content of the textbox, for example if you have used AdSense when you grab code from AdSense the selection never changes and your unable to alter the code in the textbox.
Any solutions would be appreciated.

Sounds like you want the the text box to be read-only. However, I would say that preventing the user from changing the selection is a bad idea: it's confusing and inconvenient for the user, so I haven't implemented that. The following will select the input's content when focussed in all browsers, and the input is read-only:
<input type="text" id="foo" readonly value="Some text">
<script type="text/javascript">
var textBox = document.getElementById("foo");
textBox.onfocus = function() {
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
};
</script>

I altered the code by Tim Down to get it work the way it should, here is the final code for other people ( make sure to capitalize O in readOnly ).
<script type="text/javascript">
function selectAll(id) {
var textBox = document.getElementById(id);
textBox.select();
textBox.readOnly = true;
textBox.onmouseup = function() {
textBox.select();
return false;
};
textBox.onmousedown = function() {
textBox.select();
return false;
};
};
</script>

<html>
<body>
<script>
function getElement(elemname)
{
if (document.getElementById)
return document.getElementById(elemname);
else if (document.all)
return document.all[elemname];
return 0;
}
function lockingSelect()
{
ta = getElement("mytext");
ta.select();
ta.readonly = true;
}
</script>
<textarea id = "mytext"></textarea>
<br>
<input type=button onclick="lockingSelect();" value="lock"/>
</body>
</html>

Related

How to replace content area with an iframe when a button is clicked, via javascript?

I have a content area in which I want to display certain text when the page loads and the same text when a button is clicked (biography). When a different button is clicked (AFT), I want the text in the content area to be replaced with the content of a URL via an iframe.
I have managed to get the right text to display when the page loads, but when I click the 'AFT' button the text is replaced with "[object HTMLIFrameElement]" instead of displaying the iframe. Does anyone know whats going wrong?
HTML code:
<div id="content" >
<script src="myJS.js"></script>
<script> displayBiography(); </script>
<iframe src="cwExample.pdf" name="iframe" id="iframe1"></iframe>
</div>
<div id="leftBar">
<br><br>
<button class="button" type="button" onclick="displayBiography();">
Biography </button>
<h3> Samples of Work </h3>
<button class="button" type="button" onclick="toShow();"
target="#iframe1"> AFT </button>
JS Code:
var content = document.getElementById("content");
var biography = "<p> Text here </p>"
;
function displayBiography() {
"use strict";
content.innerHTML = biography;
}
window.onload = function() {
var iframe = document.getElementById('iframe1');
iframe.style.display = 'none';
}
function toShow() {
var iframe1 = document.getElementById('iframe1');
content.innerHTML = iframe1
biography.style.display = 'none';
iframe1.style.display = 'block';
}
There are different solutions, depending on what your future aim could be. But in general, using an iFrame is not recommended at all.
Hard coded text
If the text is static and doesn't need to be changed after coding, you can simply set the text with JS, without jQuery.
HTML
<div id="content">
</div>
JavaScript
window.onload = function() {
showBio();
// add event listeners to the buttons
}
function showBio() {
var bio = "blabla";
setContent(bio);
}
function showSmthElse() {
var txt = "other blabla";
setContent(txt);
}
function setContent(newContent) {
var div = document.getElementById("content");
if( div != null ) {
div.innerHTML = '';
div.insertAdjacentHTML = content;
}
}
Load text from database
If you want to change the text, give others the opportunity to change it or want to save multiple bios, think about storing them in a database on your server (if this is possible with your structure). In this case you should think about using AJAX. It's a technique to load data from a server without refreshing the page. There are a lot of tutorials on the web and many questions are already answered here. It's really not that difficult :)

parse html textfield to javascript

Hello I have a question and I've been googling it before asking to you guys and I can't find the solution. I would like to have the data-id="video" added in a textbox so that I can change it without changing the source file everytime.
<div class="youtube-container"><div class="youtube-player" data-id="VIDEO"></div></div>
Is it possible that I can change the "VIDEO" with a textfield??
I have a javascript that loads the video so that I can just type in a video id.
Hope someone can help me with this.
Below is the code that calls for the video id.
(function() {
var v = document.getElementsByClassName("youtube-player");
for (var n = 0; n < v.length; n++) {
var p = document.createElement("div");
p.innerHTML = labnolThumb(v[n].dataset.id);
p.onclick = labnolIframe;
v[n].appendChild(p);
}
I forgot to post this the first time.
For parse:
$(".youtube-player").data("id")
For change content:
$(".youtube-player").data("id","NEW CONTENT")
how are you want to change it - on your choice, with select or textfield
You must add input
<input type="text">
And this jQuery code
$('input').on('change', function() {
$('.youtube-player').data('id', $(this).val());
});

Fire an event before `cut` event in ace editor

I want to fire an event before cut, so that I can get what text is being cut i.e. what has been already selected. I am currently using the following code, which doesn't seem to work as desired.
$("#editor").bind({
cut:function(){
console.log('Cut Detected');
alert(editor.selection.getRange());
}
});
editor is the id of the "div" tag which is editable. editor.selection.getRange() returns the start and end of selection.
edit I am woring with content editable div and want to apply the functionality on it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Editor</title>
</head>
<body>
<div id='myTa' contenteditable>hello world where are you</div>
<script type='text/javascript' src='jquery-2.1.4.min.js'></script>
<script type='text/javascript'>
$("#myTa").on("cut", function(){
alert(this.selectionStart+ " to " + this.selectionEnd);
})
</script>
</body>
</html>
You are correct that you need to use the cut event. The ClipboardEvent API is apparently unstable but yes, I would have thought it would include the text being moved onto the clipboard.
The following works for me:
$("textarea").on("cut", function(){
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
It's worth noting that bind is deprecated in jQuery, you should use on instead. Try out the snippet:
$("textarea").on("cut", function() {
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
I think at first that clipboardEvent will have the clipped text, but it seems not, so I try to find the selection related properties of input and found it.
And the reference is HTMLInputElement.
This codes work in presumption that your $("#editor") is either an input or textarea.
$("#editor").bind({
cut:function(e){
console.log('Cut Detected');
var $this = $(this);
var selectStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var clippedValue = $this.val().slice(selectStart, selectionEnd);
// Now you have the clipped value, do whatever you want with the
// value.
alert(clippedValue);
}
});
For works on contentediable, you can do this, which I just found info from Return HTML from a user-selected text and MDN
$("#myTa").on("cut", function(e){
// Seems diff bro
var selections = window.getSelection();
var currentSelection = selections.getRangeAt(0);
var start = currentSelection.startOffset;
var end = currentSelection.endOffset;
var selectedContents = currentSelection.toString();
// Do whatever you want.
console.log(start, end);
console.log(selectedContents);
alert(selectedContents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='myTa' contenteditable>ask;ndjkasn asdbasj aujs d sdib askjbnsaab asbh mjn a</div>
I have got the solution to my answer. apperently there is an editor.on('cut',function(e)) in ace editor I use
editor.on("cut", function(e){
console.log('Cut Detected');
console.log(editor.selection.getRange());
});

how do you make a text input field open different links based on user input

I can't imagine this is very hard but i've been trying to figure out the best way to do this and honestly im completely lost. Now im getting frustrated so it would be great if someone who knows how to do this exactly could help me out.
I need a textbox I can embed into my html script, that will open different links depending on the users input text.
So in english here is the basics of what I need. A working script would be very much appreciated for I am stumped.
* stands for “any characters”
If text input contains bbb open link htttp://example1.com/bbb
otherwise
If text input contains *zzz* open link htttp://example2.com/something-predefined*zzz*
otherwise
If text input contains *xxx* open link htttp://example3.com/something-predefined*xxx*
otherwise
If text input contains * open link htttp://example3.com/*
Pseudocode:
function parmatch(input):
if input matches /^bbb$/
open 'http://example1.com/{input}'
return
if input matches /zzz/
open 'http://example2.com/something-predefined{input}'
return
if input matches /xxx/
open 'http://example3.com/something-predefined{input}'
return
MDN's article on regular expressions in JavaScript
the following code only example for what you ask. here change the <a href=""> for console.
<input type="text" id="picker" />
$('#picker').keyup(function() {
var value = $("#picker").val();
if(value == "1")
{
console.log("go to home");
}
else if(value == "2")
{
console.log("go to login");
}
else
alert("plz enter valid input");
})
For a more complete answer, I'd suggest the following:
var btn = document.getElementById('fire'),
input = document.getElementById('demo'),
output = document.getElementById('output'),
pageMap = {
'aaa' : 'pageA',
'bbb' : 'pageB',
'ccc' : 'pageC'
};
function loadPage (input, output, map) {
var v = input.value,
url = 'http://example.com/',
text = 'textContent' in document ? 'textContent' : 'innerText';
for (var i in map) {
if (map.hasOwnProperty(i) && v.indexOf(i) > -1) {
// the following shows the URL you'd end up with
output[text] = url + map[i];
// to *load* the URL, remove the above line,
// and uncomment the following:
// window.location = url + map[i];
}
}
}
btn.addEventListener('click', function(e){
e.preventDefault();
loadPage(input, output, pageMap);
});
JS Fiddle demo.
This answer is, however, not to encourage you to avoid learning JavaScript (as suggested in the comments to Ignacio's answer); please take the time to read, at least, the references I've supplied below.
References:
document.getElementById().
Element.addEventListener().
event.preventDefault().
for...in loop.
JavaScript object syntax.
window.location.

Inserting text into an editable IFRAME at the caret position (IE)

I'm struggling with an actually straighforward problem: In Internet Explorer I want to insert plain text at the current caret position. This works really fine for simple TEXTAREA elements but it doesn't entirely work for editable IFRAMEs, which is what I have.
In the script I use I am creating a TextRange object from the document of the IFRAME which I use to paste the text as HTML at the cursor position.
<iframe id="editable">
<html>
<body>
Some really boring text.
</body>
</html>
</iframe>
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.body.innerHTML = iframe.textContent || iframe.innerHTML;
// Make IFRAME editable
if (doc.body.contentEditable) {
doc.body.contentEditable = true;
}
}
function insert(text) {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
iframe.focus();
if(typeof doc.selection != 'undefined') {
var range = doc.selection.createRange();
range.pasteHTML(text);
}
}
</script>
<input type="button" value="Insert" onClick="insert('foo');"/>
When I select some text in the IFRAME, the selection will be replaced with "foo" - this is expected behaviour. But when I just place the caret somewhere in the text, the insertion won't work.
Is this common behaviour, as there is "no real selection" for the case that I just place the cursor somewhere or is it a bug with editable IFRAMEs in IE, since it works pretty well with simple TEXTAREA elements?
Is there a workaround?
You may find it works if you use onmousedown rather than onclick in your button.
UPDATE
The reason why this makes a difference is that the click event fires after the iframe has lost focus (which destroys a collapsed selection in IE) whereas mousedown fires before.
FURTHER UPDATE
You could also try fixing this in IE by saving/restoring the selected TextRange as the iframe loses/receives focus. Something like this should work:
function fixIframeCaret(iframe) {
if (iframe.attachEvent) {
var selectedRange = null;
iframe.attachEvent("onbeforedeactivate", function() {
var sel = iframe.contentWindow.document.selection;
if (sel.type != "None") {
selectedRange = sel.createRange();
}
});
iframe.contentWindow.attachEvent("onfocus", function() {
if (selectedRange) {
selectedRange.select();
}
});
}
}
window.onload = function() {
var iframe = document.getElementById('editable');
fixIframeCaret(iframe);
};

Categories

Resources