pat27
pat27

Reputation: 39

How to select automatically a text input?

I want a text input selected (as if I had clicked on) when I click on another element on the page. I can't figure out how to do it?

Upvotes: 1

Views: 328

Answers (3)

Mutai Mwiti
Mutai Mwiti

Reputation: 487

Try this. I have not tried it though. It's worth noting that it is based on jquery.

//set focus by default
$("your_input").focus();
//if the focus is lost set it again
$("div").focusout(function(){
    $("your_input").focus();
});

Upvotes: 0

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

You are looking for this: pure js way

<img src="http://placehold.it/350x150" 
onclick="document.getElementById('target').focus(); return false;">

<input type ="text" id="target"/>

Clicking on image will set focus on the text field.

Upvotes: 2

Maciej Caputa
Maciej Caputa

Reputation: 1891

Assuming that your input field has id #input then solution would be

// Wrapper function needed to ensure that DOM elements have been already rendered.
(function() {

  $( '#input' ).focus(); // jQuery

  document.getElementByID( 'input' ).focus(); // VanillaJS

})();

Upvotes: 0

Related Questions