最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Focus on first form element inside span when span is clicked - Stack Overflow

programmeradmin1浏览0评论

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>
发布评论

评论列表(0)

  1. 暂无评论