I have an old asp.net app originally at .net 2.0 which framework is upgraded to 4.0 (this is not related to my problem, just informing in details) and I'm using Internet Explorer 11. Here I'm facing a problem, I have a text box as shown bellow:
<asp:TextBox ID="txtCost" runat="server" onKeyPress="return GetSelected();" MaxLength="12" TabIndex="6"></asp:TextBox>
In where I'm trying to check on onKeyPress if the user has selected/highlighted any content and trying to get the selected content. To do this I tried bellow code
JS:
function GetSelected() {
var pass = true;
var content = document.getElementById('<%= txtCost.ClientID %>').value;
if (content.length == 2 && key !== 46) {
if (document.getSelection != undefined) { //true, if there is any selected content
//do something with selected content
pass = false;
}
else //if no content selected then return false
{
pass = false;
}
}
return pass;
}
but here if (document.getSelection != undefined) is always true even though there is no text selected in the text box. I need an if condition be true only if there is any selected text in that text box. Well, as I know document.getSelection returns a selectionRange object but I'm not very clear how document.getSelection works. Please help me to fix this.
Bellow are few referrals I followed
link_1,
link_2
Related
I have this code, which displays or hides text blocks according to the button pressed. The menu is from two buttons, and when one button is pressed it triggers the text to be displayed and hides another text.
The code works fine on chrome, but on safari, only the first piece of code works (the one which adds a new class to the button). What could be an issue here?
I tried to test by printing the button text (just before alert("The browser shows this alert");) and the code prints button text correctly. But I can't get into the if().
$(".about-us-button1").on('click', function () {
$(".about-us-button1").removeClass('active');
var button = $(this);
$(this).addClass('active');
for (var i = 0; i < button.length; i++) {
var name = button[i].innerText;
alert("The browser shows this alert");
if (name === 'Cargo booking form' || name === 'Krovinių užsakymo forma' || name === 'ЗАКАЗ') {
alert('The browser not reaching this piece of code');
$(".cargo-booking").addClass('visible');
$(".request-cargo").removeClass('visible');
}
if (name === "Request about cargo" || name === "Užklausa apie krovinį" || name === "Запрос Стоимости") {
$(".cargo-booking").removeClass('visible');
$(".request-cargo").addClass('visible');
alert('The browser not reaching this piece of code');
}
}
});
After running the command console.log(escape(name)) I got a different results at Chrome: Request%20about%20cargo and Safari: <h2>Request about cargo</h2>
I can't find a simple way to get a text from an HTML object, that works on all browsers.
try to change
var name = button[i].innerText;
to this:
var name = button[i].textContent;
I am pretty new to JavaScript and got stuck at one point:
I am using asp control fileupload to upload some files and store them to database, i am using asp repeater control to show all the docs in database in front end and have associated a html checkbox to every doc:
The problem is when i check or uncheck the checkbox, the delete button enables/disables accordingly, but when i click the "Select All" button where i am calling both functions - to check all checkboxes and to enable button, somehow the delete button is not getting enabled..Please help.
Here is JavaScript Code to enable delete button:-
function EnableButton() {
var rpt = document.getElementById('<%= rptWordDoc.ClientID %>');
var chkbx = document.getElementsByTagName('input');
var x = document.getElementById("btnDelWordDoc");
for (i = 0; i <= chkbx.length; i++) {
var id = "rptWordDoc_chkWordDoc_" + i
var y = document.getElementById(id);
if (y == null) {
break;
}
if (y.checked == true) {
x.disabled = false;
break;
}
else {
x.disabled = true;
}
}
}
This is how i am calling the function:-
<asp:Button ID="btnSelectAll" runat="server" Text="Select All" OnClientClick="fnSelectAll(); JavaScript:EnableButton();" />
Through Checkbox:-
<input type="checkbox" id="chkWordDoc" runat="server" onclick="JavaScript:EnableButton();" />
You called two functions fnSelectAll(); and JavaScript:EnableButton(); may be second is not executed after executing the first one.
Finally found the cause:
Actually i was using asp: button control for Select All & Clear All features and thus it was posting back to the server and setting back the value of delete button enabled attribute to false.
I added a html control instead of asp button for Select All & clear all buttons and didn't added runat=server attribute since no server side event was required.
Thanks for your suggestions..
Cheers..:)
How can get the selected text from a textbox/textarea if I don't know which one active (focused). I am trying to create a small bookmarklet that will correct the selected text in any type of input on a page.
For the selection, you want selectionStart and selectionEnd.
As for the currently focused element, use document.activeElement.
So as a combination you can use: http://jsfiddle.net/rBPte/1/.
As Tim Down pointed out, you'd need a more complex solution for Internet Explorer version 8 or lower: Caret position in textarea, in characters from the start
function getText(elem) { // only allow input[type=text]/textarea
if(elem.tagName === "TEXTAREA" ||
(elem.tagName === "INPUT" && elem.type === "text")) {
return elem.value.substring(elem.selectionStart,
elem.selectionEnd);
// or return the return value of Tim Down's selection code here
}
return null;
}
setInterval(function() {
var txt = getText(document.activeElement);
document.getElementById('div').innerHTML =
txt === null ? 'no input selected' : txt;
}, 100);
I have text boxes <input type='text'> that only allow numeric characters and wont let the user enter a dot (.) more than once. Problem is, if the text in the text box is selected, the user intends to overwrite the contents with a dot, hence making it allowed! The question is, how can you tell in javascript whether the text in that text box is selected or not.
Thanks
The following will tell you whether or not all of the text is selected within a text input in all major browsers.
Example: http://www.jsfiddle.net/9Q23E/
Code:
function isTextSelected(input) {
if (typeof input.selectionStart == "number") {
return input.selectionStart == 0 && input.selectionEnd == input.value.length;
} else if (typeof document.selection != "undefined") {
input.focus();
return document.selection.createRange().text == input.value;
}
}
2017 Specific Answer - Faced the same issue recently.
We were allowing users to enter only 3 digits at a time. When the user tried to enter the fourth character we returned false.
This became an issue when the user had a selection and was trying to overwrite the values.
Taking a hint from Tim's answer. I understood that I wanted to see if the selection value was same as the input's value.
In modern browsers I achieved it by doing:
document.getSelection().toString() === input.value // edited
Hope this helps someone.
For anyone who needs the code to get at the selected text within a textbox, here's an enhanced version:
http://jsfiddle.net/9Q23E/527/
function getSelection(textbox)
{
var selectedText = null;
var activeElement = document.activeElement;
// all browsers (including IE9 and up), except IE before version 9
if(window.getSelection && activeElement &&
(activeElement.tagName.toLowerCase() == "textarea" || (activeElement.tagName.toLowerCase() == "input" && activeElement.type.toLowerCase() == "text")) &&
activeElement === textbox)
{
var startIndex = textbox.selectionStart;
var endIndex = textbox.selectionEnd;
if(endIndex - startIndex > 0)
{
var text = textbox.value;
selectedText = text.substring(textbox.selectionStart, textbox.selectionEnd);
}
}
else if (document.selection && document.selection.type == "Text" && document.selection.createRange) // All Internet Explorer
{
var range = document.selection.createRange();
selectedText = range.text;
}
return selectedText;
}
Instead of hitting the wall of digits dots and selections you can climb it easily by checking the value in onchange event.
HTML:
<input type="text" onchange="ValidateNumericValue(this);" />
JS:
function ValidateNumericValue(oInput) {
var blnRequired = true; //set to false if allowing empty value
var sValue = oInput.value;
if (blnRequired && sValue.length == 0) {
alert("Please enter a value");
oInput.focus();
return;
}
var numericValue = parseFloat(sValue);
if (isNaN(numericValue)) {
alert("Value is not a valid number");
oInput.focus();
return;
}
//put back to make 2.15A back to 2.15
oInput.value = numericValue + "";
}
This will check the value when changed (and user go to different element) and when not valid will alert and set focus back.
Live test case: http://jsfiddle.net/yahavbr/NFhay/
You can get the id of the selected element in the page with the following code:
elem_offset = document.getSelection().anchorOffset;
elem = document.getSelection().anchorNode.childNodes[elem_offset];
alert(elem.id);
If you're use case is simply to know whether any text is selected.
The difference between selectionStart and selectionEnd is always zero when no text is selected irrespective of cursor position.
So this should do the trick
const element = document.getElementById('inputbox');
const isTextSelected = element.selectionStart - element.selectionEnd;
I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.
How can I do it?
When I click the submit button for the textbox below, the message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.
If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.
Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.
How is it to be done?
OK, here is the code I have:
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{ // Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of Internet Explorer 6 on my current system. Perhaps it will work for you, and that's why I give it.
The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.
I got the right result (the selection content) with the onKeyDown event:
document.onkeydown = function (e) { ShowSelection(); }
So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.
I didn't have any success with a button drawn with a li tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple input button, though...
Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:
document.querySelector('textarea').addEventListener('mouseup', function () {
window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
// window.getSelection().toString();
});
<textarea>
Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>
This works in all browsers.
If you also want to handle selection via the keyboard, add another event listener for keyup, with the same code.
If it weren't for this Firefox bug filed back in 2001 (yes, 14 years ago), we could replace the value assigned to window.mySelection with window.getSelection().toString(), which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.
function disp() {
var text = document.getElementById("text");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />
For Opera, Firefox and Safari, you can use the following function:
function getTextFieldSelection(textField) {
return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}
Then, you just pass a reference to a text field element (like a textarea or input element) to the function:
alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));
Or, if you want <textarea> and <input> to have a getSelection() function of their own:
HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
var ss = this.selectionStart;
var se = this.selectionEnd;
if (typeof ss === "number" && typeof se === "number") {
return this.value.substring(this.selectionStart, this.selectionEnd);
}
return "";
};
Then, you'd just do:
alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());
for example.
I am a big fan of jQuery-textrange.
Below is a very small, self-contained, example. Download jquery-textrange.js and copy it to the same folder.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery-textrange</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery-textrange.js"></script>
<script>
/* Run on document load */
$(document).ready(function() {
/* Run on any change of 'textarea' **/
$('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {
/* The magic is on this line **/
var range = $(this).textrange();
/* Stuff into selectedId. I wanted to
store this is a input field so it
can be submitted in a form. */
$('#selectedId').val(range.text);
});
});
</script>
</head>
<body>
The smallest example possible using
<a href="https://github.com/dwieeb/jquery-textrange">
jquery-textrange
</a><br/>
<textarea id="textareaId">Some random content.</textarea><br/>
<input type="text" id="selectedId"></input>
</body>
</html>
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);
// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);