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>
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>
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.
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.
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.
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>
See original demo for jQuery 1.3 - 1.8 compatible code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With