admin管理员组

文章数量:1317915

I can't figure out how to focus on the first form element inside a span when the span is clicked. I've included my code, I had also messed around with 'closest' but had no luck.

<form>
<span>
  <input id="content" type="text">
  <label for="content">Content</label>
</span>
</form>

$('span').click(function() {
    $(this).find('input').focus()
});

Any help is appreciated.

I can't figure out how to focus on the first form element inside a span when the span is clicked. I've included my code, I had also messed around with 'closest' but had no luck.

<form>
<span>
  <input id="content" type="text">
  <label for="content">Content</label>
</span>
</form>

$('span').click(function() {
    $(this).find('input').focus()
});

Any help is appreciated.

Share Improve this question asked Mar 22, 2013 at 23:36 cianzcianz 1592 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Before answering your actual question: there is a way to achieve what you're trying to do which doesn't even require any JavaScript.

If you wrap your input field in the label tag, clicking the label will automatically give focus to the field.

<form>
    <label>
        Content
        <input id="content" name="content" type="text">
    </label>
</form>

If you insist on doing it through JavaScript/jQuery, you'll have to make sure you only attach the click handler after the DOM is ready:

$(document).ready(function () { // Or equivalent: $(function() { ... });
    $('span').click(function () {
        $(this).find('input:first').focus(); // :first makes sure only the first input found is selected
    });
});

why not use the label to trigger this functionality the span will only cover the label and input so if i understand correctly you want the focus to be set on the input even when the user clicks the lable which can be achieved like so:

<form>
    <span>
       <input name="content" id="content" type="text">
       <label for="content">Content</label>
    </span>
</form>

But if you are trying to do something else then:

$(document).ready(function(){
   $('span').click(function() {
     $(this).find('input:first').focus();
   });
});

Make sure your js is called after the DOM is loaded

<script type="text/javascript">
  $(function(){
    $('span').click(function() {
      $(this).find('input').focus()
    });
  });
</script>

本文标签: javascriptFocus on first form element inside span when span is clickedStack Overflow