4

I have two input, one static:

<input type="text" class="someclass" />

and other dynamic:

$("<input />", {
    type: "number",
    min: "0"
}).addClass("someclass").appendTo($("#someid"));

and this code works fine in static input:

$(document).on("focusout", ".someclass", function(){ alert("hello!");});

But for dynamic input generate infinite loop with the alert, this happen only in Chrome, someone has any idea?

error is when focus go on the other input with the same class

user7420251
  • 41
  • 1
  • 4
  • 1
    A wild guess here: probably because when an alert box is closed in Chrome, a focusout event is registered? Anyway, using `alert()` is not a good way to troubleshoot or test new features as it blocks code execution. Try using `console.log()` instead. – Terry Jan 15 '17 at 01:59
  • Your code seems OK in Chrome: https://jsfiddle.net/ymazyrmn/. Maybe there is another code in your page that is triggering the repeating focusout event. – Kalimah Jan 15 '17 at 02:01
  • i have the same problem... my chrome is Versión 55.0.2883.87 m (64-bit) – user7420251 Jan 15 '17 at 02:03
  • third question in a week that I've read regarding chrome focus / blur events and `alert` ... I agree with first comment, don't use `alert` - there are libraries available to make non-blocking (but still have a "modal" feel) alerts which won't fail this way - e.g. alertify – Jaromanda X Jan 15 '17 at 02:20
  • @Kalimah Apps is when focus go on the other input – user7420251 Jan 15 '17 at 02:20

1 Answers1

5

As Terry have stated, the alert box is not the best way to troubleshoot any JS issue.

Replacing alert with console.log() shows that the event is triggered only once in Chrome and other browsers.

$("<input />", {
  type: "number",
  min: "0"
}).addClass("someclass").appendTo($("#someid"));

$(document).on("focusout", ".someclass", function() {
  console.log("alert");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="someclass" />
<div id='someid'>

</div>

See this answer:

I think it's because the the browser is sending focus from the alert to your text field every time you click the alert's "OK" button. You're probably not going to be popping up an alert (methinks) in the final version of your code, so this might not be an issue in the long run.

https://stackoverflow.com/a/6869420/529024

Community
  • 1
  • 1
Kalimah
  • 11,217
  • 11
  • 43
  • 80
  • Yes!!, error only happen with alert(); with console.log and other instructions works fine, thank you very much !!! – user7420251 Jan 15 '17 at 02:43