0

This is my code:

Javascript:

$(".test").on("focusout", function (e) {
        $("#output").append("Lost focus<br>");
});

HTML:

Inputs inside div:
<div class="test">
    <input type="text" />
    <input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">

</div>

I want to detect if user leaves "div.test". Unfortunately, "focusout" works also when I move focus to other object inside this div.

Look at this fiddle: http://jsfiddle.net/Piotrek1/wfukje3g/6/

Click on first input and use Tab to switch through textboxes. " Lost focus" should appear only if user move out from the div, but it happens always. Why is that and how to change it?

Piotrek
  • 10,919
  • 18
  • 73
  • 136

2 Answers2

0

The $ operator returns a collection. You have two inputs inside the <div class="test">. So it matches all elements and children with the .test class.

I think what you want two divs with separate input elements and two different classes OR, use an ID on the actual input element so the $ operator only matches the input id you want this event to fire on. http://jsfiddle.net/wfukje3g/7/

$("#test").on("focusout", function (e) {
            $("#output").append("Lost focus<br>");
    });
        <div class="sometest">
        <input id="test" type="text" />
        <input type="text" />


      </div><br>
        Inputs outside div:<br>
        <input type="text" />
        <div id="output">

    </div>
James Montagne
  • 77,516
  • 14
  • 110
  • 130
tyoungjr
  • 187
  • 1
  • 12
0

I have implemented piece of code to handle div focus out

$(document).ready(function () {
 var count = 1;
  $("#name").focusout(function (e) {
     if($(this).has(e.relatedTarget).length === 0) {
         $("#output").append("<label style='width:100%;'>"+ count++ +" Name div focus out </label>"); 
        }
  });
});
Inputs inside div:
<div id="name" class="test">
    <input type="text" id="firstname"/>
    <input type="text" id="lastname"/>
</div>
Inputs outside div:<br>
<input type="text" id="dob"/>
<div id="output" style="width:100%"></div>

In this piece of code I have used relatedTarget. relatedTarget will provide the next focused element If next element is not the child of this div then it is div focus out. Try this in your code.

I hope this will be helpful.

Thanks

JSFIDDLE LINK - Sample code

Mahipat
  • 611
  • 1
  • 5
  • 12