In Safari, using jQuery, the form input textbox does not receive focus after warning is displayed. What for?

I have an ASPX web form. I am using jQuery for just my Javascript. I am using a Javascript script validation to validate each of the values ​​of the form fields. If an error occurs, I display a warning with an error message. Then I move focus to the base element.

Here are the examples I've tried.

Using jQuery:

var Form_FieldDef = function(name) {
    this.name = name;
    this.SetFocus = function() {
        $('#' + this.name)[0].focus();
    }
    this.Validate = function() {
        var isvalid = true;
        if ( $.trim($('#' + this.name).val()) == '') {
            alert("Your entry is empty");
            this.SetFocus();
            isvalid = false;
        }
        return isvalid;
    }
}

      

This works on IE7, IE8, Opera, Chrome and Firefox. It doesn't work on Safari 4 on PC. I don't have a Mac.

So, I changed the SetFocus method to this.

this.SetFocus = function() {
    var fld = document.getElementById(this.name);
    if (fld != null)
        fld.focus();
}

      

This works on IE7, IE8, Opera, Chrome and Firefox. It doesn't work on Safari 4 on PC.

I walked through the code using the VS 2008 debugger and I am calling the focus method on the base element.

+2


a source to share


2 answers


That's a guess: try changing focus in the timeout routine:



this.setFocus = function() {
  var self = this;
  setTimeout(function() {
    $(self).focus();
  }, 1);
};

      

0


a source


My own guess: It is possible that your use of 'this' inside anonymous functions refers to any anonymous function that appears inside, making the use of 'this' ambiguous. Perhaps this slight modification will behave differently (untested):



var Form_FieldDef = function(name) {
    var parentRef = this;
    this.name = name;
    this.Validate = function() {
        var isvalid = true;
        var elem = $('#' + parentRef.name);
        if ($.trim(elem.val()) == '') {
            alert("Your entry is empty");
            elem.focus();
            isvalid = false;
        }
        return isvalid;
    }
}

      

0


a source







All Articles