Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all text on focus using jQuery

Tags:

I have a little jQuery function that is meant to automatically select text in an asp.net text box when it gets focus. However, the text in the text box gets selected, but immediately then deselects.

The code works if i bind to the focus event with .focus(function()) but I am adding the text boxes to the page dynamically which is why I think I need to use the live event.

Can anyone see a problem? The text boxes in question are in Item templates of two gridviews inside a multiview if that makes a difference?

Code:

<script type="text/javascript">      //Select all text in Cost Rate Text Boxes when they have focus     $(document).ready(function () {         $(".CostRateTextBox").live('focus', function () {             $(this).select();         });      });  </script> 

enter image description here

Edit:

<script type="text/javascript">      //Select all text in Cost Rate Text Boxes when they have focus     $(document).ready(function () {         $(".CostRateTextBox").live('focus', function () {             $(this).select();             preventDefault();         });      });  </script> 
like image 950
WraithNath Avatar asked May 25 '11 12:05

WraithNath


People also ask

How do you select all text in input on focus?

select to select all the text in the input as the value of the onFocus prop. e. target is the input element so we can call select on it to select all the text.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.

How do you auto select an input field and the text in it on page load?

To auto select an input field and the text in it on page load with JavaScript, we can use the focus and select methods. to add an input. const input = document. getElementById("myTextInput"); input.


1 Answers

It seems to be the mouseup event interfering. You'll notice if you click and hold in the form field then move outside of it to "mouseup" the selection sticks. Using mouseup instead of focus to trigger the select() method seems to work well:

<script type="text/javascript">      //Select all text in Cost Rate Text Boxes when they have focus     jQuery(function($){         $("table.demo").on("mouseup", ".CostRateTextBox", function () {             $(this).select();         });     });  </script> 

Demo: jsfiddle.net/gableroux/jvJzX/12

See original demo for jQuery 1.3 - 1.8 compatible code.

like image 179
Marcel Avatar answered Oct 09 '22 20:10

Marcel