Jquery Focus() in Firefox

Asked

Viewed 383 times

2

Good morning,

I have a problem with firefox. I have a methods that clears an input with a value I consider invalid ai in the sequence I give Focus to that input. In Internet Explorer and Chrome it works.

The methods I use are these:

$(".field-date").blur(function () {
    if (!DtValida(this.value)) {
        MsgAlerta("Data inválida.");           
        this.value = "";
        this.focus();
        return false;
    }
    return true;       
});

In Firefox clears the input and shows the message, only the Focus that doesn’t work at all.

2 answers

3


First of all, good morning, Kaique. From what I researched here there is a workaround for that Issue. Try waiting for the next "tick" to run Focus.

setTimeout(function() {
        $(this).focus();
    }, 0);

UPDATE

It is worth remembering that within the function setTimeout() the $(this) has another scope, so it is necessary to focus on the selected element.

For this, just put exactly the element:

setTimeout(function() {
            $(".field-date").focus();
        }, 0);

I hope I’ve helped.

  • Andrew would look like this? $(". field-time"). Blur(Function() { if (!Timevalido(this.value)) { Msgalerta("Invalid time." ); this.value = ""; setTimeout(Function() { $(this). Focus(); }, 0); Return false; } Return true; });

  • Exactly. When do you put setTimeout() with a value of 0, Javascript waits for the Event loop to execute the instruction later. It tests and warns me.

  • So I tested the code I put in the previous answer, I switched pro setTimeout and it worked for IE and Chrome, but for Firefox it still didn’t work.

  • Instead of $(this).focus();, place $(".field-date").focus(). Here worked perfectly.

  • Must have some script of mine interfering so here still two 3 browsers the only one that doesn’t work is firefox.

  • Kaique, you must be putting it wrong. Really put yourself just this.focus() or $(this).focus() here also did not work. It is a problem in Firefox. However, putting the selector ". field-date" worked.

Show 1 more comment

0

It worked that way:

classe.blur(function () {
    var componente = $(this);

    if (!DtValida(this.value)) {
        MsgAlerta("Data inválida.");
        componente.val("");
        setTimeout(function () {
            componente.focus();
        });
        return false;
    }
    return true;
});

I had tried with setTimeout previously and it didn’t work there I took the last parameter o of the interval ai worked, I didn’t understand well what it changes I will search better.

About using the selector with the class caused me a problem because I have more than one element with this class, then Focus always went to the last one. Ai searched the selector again instead of using this direct thanks to the scope tip in Andrew’s update.

Thanks for your help Andrew.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.