Robin I Knight
Robin I Knight

Reputation: 173

JQuery onclick function to focus input

I want a JQuery function that means if the user clicks on some text on the page it focuses an input.

$(document).ready(function(){
$('#header.search span').click(function(){
    $('#header.search input').focus();
});
});

That did not do anything. On Firebug nothing is registered.

Any ideas?

Marvellous

Upvotes: 12

Views: 95016

Answers (4)

Gurpreet Singh
Gurpreet Singh

Reputation: 383

$( "input" ).focus(function() {
  $( this ).next( "span" ).css( "display", "inline" ).fadeOut( 1000 );
});
span {
    display: none;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text"> <span>focus fire</span></p>
<p><input type="password"> <span>focus fire</span></p>

https://api.jquery.com/focus/

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

If you have id to the input element then you dont need javascript to do this. You can use for attribute with a label tag pointing to the input element id. Try this

Working demo

<label for="input1">Name</label>
<input id="input1" type="text" />

If you click on Name text the focus will be set into the input field.

Upvotes: 20

Obi
Obi

Reputation: 49

I think $('#header.search input') returns a bunch of INPUTs, not just one, so JQuery may not know which one to focus. You'll need to decide which one to focus.

Upvotes: -1

Henry
Henry

Reputation: 2187

http://jsfiddle.net/HenryGarle/LXngq/

<span>
    <br>
        Span
    <br>
    <input id="InputToFocus" type="text">
</span>

$('span').click(function(){
    $('#InputToFocus').focus();
});

Seems to be working fine, It is probably a problem with your selectors. Could you post the structure of your HTML surrounding the input?

Upvotes: 27

Related Questions