Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if the text in a textbox is selected?

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

like image 744
Jimbo Avatar asked Feb 15 '11 09:02

Jimbo


People also ask

How do you find out which TextBox is currently selected?

activeElement , you can check its nodeName. if (document. activeElement. nodeName == 'TEXTAREA' || document.

How do you know if an element is selected?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} . The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.

Which tag is used for TextBox?

We create TextBox by <input> tag with type="type_name" attribute.

How do I select a text box in HTML?

HTML | DOM Input Text select() Method The DOM Input select() method selects all the text content of a textarea or an input element which contains the text field. Syntax: element. select();


1 Answers

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;     } } 
like image 74
Tim Down Avatar answered Sep 17 '22 14:09

Tim Down