user1535268
user1535268

Reputation: 131

Issue with IE7 and jquery

I wrote a function that I tie to phone number in a from where I want it formatted as XXX-XXX-XXXX. This is working fie in Chrome, FF and IE8+ but not in IE7. Wondering if anyone sees anything wrong with the code or that is not compatible with IE7. In IE7 each time you enter any character it will erase it similar to what it is supposed to do once you are over 12 characters

(function( $ )
{
// This function formats a text field to a US 
// phone number as the user types the information.

$.fn.usphone = function() 
{
this.bind("change keyup input",function() 
{
 var curchrindex = this.value.length;
 var curval = $(this).val();
 var strvalidchars = "0123456789-";
 var onlyDigits = curval.replace(/\D/g,'');

 for (i =0; i < this.value.length; i++)
 {
      var curchar = curval[i];
      if (strvalidchars.indexOf(curchar) == -1) 
      {
       //delete the character typed if this is not a valid character.
       $(this).val(curval.substring(0, i) + curval.substring(i+1, this.value.length));
       return false;
      }
 }

 if (onlyDigits.length >= 10) {
    var tmpVal = '';
     for (i =0; i < 10; i++)
     {
          tmpVal += onlyDigits[i];
          if (i == 2 || i == 5) {
            tmpVal += '-';
          }
     }
    $(this).val(tmpVal);
 }


});
};
})( jQuery );

Upvotes: 0

Views: 112

Answers (1)

Brad Christie
Brad Christie

Reputation: 101604

For the same reason explained in an another question, IE7 doesn't allow you to reference string characters using the []. So where you have:

var curchar = curval[i];

IE7 is returning undefined which is then making your check fail and then forcing it to delete the character and exit. However, if you change it to:

var curchar = curval.charAt(i);
// ~~ OR ~~
var curchar = curval.substring(i,1);

You can then retrieve the single character and continue on. However, I would mention that you could use some refactoring in terms of:

  • Alternating between $(this).val() and this.value.
  • Alternating between this.value and curval (If you're going to stare a value in a variable but reference the element's original property anyways it begs the question why you assign a variable in the first place).

Upvotes: 1

Related Questions