12

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

2
  • 1
    Show us your html, and what input do you want to give focus to ? The closest one ? Commented Sep 2, 2011 at 14:50
  • It's working fine here. Commented Sep 2, 2011 at 14:51

4 Answers 4

27

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?

Sign up to request clarification or add additional context in comments.

Comments

20

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.

Comments

0

$( "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/

Comments

-1

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.

2 Comments

Ah, didn't know about JSFiddle. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.