1
$("input").focus(function(){
    console.log('input focused');
});

Above is my code to test if focus event happened.And I made a button to insert another input dynamically.But while I focus the inserted inputs,no console logged at all.

Can anybody help?

Thanks

Walter Wu
  • 43
  • 4

2 Answers2

2

You need to use event delegation with the focusin event as focus does not support bubbling(event delegation requires bubbling support to work).

$("input").focus(function() {
  snippet.log('input focus: ' + $('input').index(this));
});

$('#dynamicarea').on('focusin', 'input', function() {
  snippet.log('input focusin: ' + $('input').index(this));
});

$('button').click(function() {
  $('div').append('<input />');
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
<input />
<input />
<br />
<button>Add</button>
<div id="dynamicarea"></div>
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • thanks for the link. I have deleted the misleading answer.Thanks for not down voted the answer :) – shu Feb 26 '16 at 05:20
0
 function focused(evt){
    var target = evt.target;
    var target_name = evt.target.nodeName;
    $(target).keydown(function(e){
        if(e.which==9 && $(e.target).parent().parent().is(":last-of-type")){
            e.preventDefault();
        }else{
            $(this).unbind("keydown");
        }
    });
}
<sectionA>
<input>
/*insert input here*/
</sectionA>
<sectionB>
<input>
<input>
</sectionB>

Originally I was trying to stop focusing to the next input in the sectionB which is not in the viewport when pressing the tab. So I write a function above to bind in the inserted input to tell. But Arun's answer also work. Thanks a lot.

Walter Wu
  • 43
  • 4