pedalGeoff
pedalGeoff

Reputation: 767

Applying a Function to All Text Input Fields

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

Answers (3)

David Thomas
David Thomas

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:

Upvotes: 1

redelschaap
redelschaap

Reputation: 2834

Try this:

$(document).on('click', 'input:text', function() {
    $(this).select();
});

Upvotes: 0

A.B
A.B

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

Related Questions