简体   繁体   中英

workaround for firefox bug on focus/blur

I have written the following code to check if the value inserted in a input field already exists in the database.

$('#nome_field').blur(function(){
        var field_name=$('#nome_field').val();
        $.ajax({
          url: "check_field_unique.php",
          method: 'post',
          data: {field_name:field_name},
          dataType: "json"
        }).done(function(data){
            if(data.status==500){
              //esiste un altro campo con lo stesso nome
              bootbox.alert({
                message: data.message, 
                size: 'small',
                backdrop: true,
                callback: function(){
                    //$('#nome_field').val('');
                    $('#nome_field').focus();           
                }
              });
            }       
        });
    });

It works fine in every browser except Firefox. There is a known bug opened 20(!!) years ago that still affects Firefox that cause an infinite loop between focus and blur. When the code reaches the $('#nome_field').focus(); line it will focus but then trigger the blur again and run the validation again (infinite loop).

If I decomment this line $('#nome_field').val(''); then $('#nome_field').focus(); will never get executed but the input will be cleared. My expectation was that by cleaning the input field I'd fix the bug. Anyway the desired behaviour is to leave what was written by the user for him to fix instead of cleaning the input.

Does anyone knows how to fix this?

A work around is you can code a safety check that the blur does not happen right after you set the focus.

$('#nome_field').blur(function() {
  var tb = $(this);
  if (tb.data("ignore")) {
    return;
  }
  var field_name = tb.val();
  $.ajax({
    url: "check_field_unique.php",
    method: 'post',
    data: {
      field_name: field_name
    },
    dataType: "json"
  }).done(function(data) {
    if (data.status == 500) {
      //esiste un altro campo con lo stesso nome
      bootbox.alert({
        message: data.message,
        size: 'small',
        backdrop: true,
        callback: function() {
          //$('#nome_field').val('');
          tb.data("ignore", true)
          tb.focus();
          window.setTimeout(function () {
            tb.removeData("ignore");
          }, 100);
        }
      });
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM