Reputation: 767
I have this bit of code to auto-select the text in an input field.
onclick="this.focus();this.select()"
And am implementing it like so
<input type="text" onclick="this.focus();this.select()" value="xxxxx">
I'm thinking it would be cleaner and easier to make updates if I were to apply this code globally instead of inline.
How would I go about adding this code to all text input tags (or maybe to text input tags with a specific ID) from an an external .js file?
Upvotes: 0
Views: 3191
Reputation: 253396
As an <input />
element is automatically focused on clicking that element, you should only need this.select()
:
$('input[type="text"]').on('click', function () {
this.select();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="something" />
<input type="text" value="something else" />
<input type="text" value="something other" />
And, if you wanted to avoid jQuery for this, you could simply:
function selectThis () {
return this.select();
}
Array.prototype.forEach.call(document.querySelectorAll('input[type=text]'), function (input) {
input.addEventListener('click', selectThis);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="something" />
<input type="text" value="something else" />
<input type="text" value="something other" />
References:
on()
.Upvotes: 1
Reputation: 2834
Try this:
$(document).on('click', 'input:text', function() {
$(this).select();
});
Upvotes: 0
Reputation: 20445
you can make this global for all input of tyoe text by this code
$("input[type=text]").click(function(){
$(this).focus();
$(this).select();
///do something here
}):
Upvotes: 1