1

I want to write a program, so I can type IP address numbers between 0 and 255. My code works in IE, but not in Firefox or Chrome.

function check(obj) {
  var txt = obj.getAttribute("value");
  txt = parseInt(txt);
  if (txt > 255 || txt < 0) {
    alert("must between 0 and 255");
    obj.focus();
    obj.select();
  } else {
    if (txt > 25) {
      var next = parseInt(obj.getAttribute("id")) + 1;
      if (next < 5) {
        document.getElementById(next.toString()).focus();
      }
    }
  }
}
<input type="text" maxlength="3" id="1" onkeyup="check(this);" />
<input type="text" maxlength="3" id="2" onkeyup="check(this);" />
<input type="text" maxlength="3" id="3" onkeyup="check(this);" />
<input type="text" maxlength="3" id="4" onkeyup="check(this);" />
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
alwayslz
  • 119
  • 1
  • 8

1 Answers1

3

The current value of an input is reflected by its value property, not the value attribute. If IE is giving you the current value via getAttribute, it's a bug in IE.

You should be using obj.value, not obj.getAttribute("value").


It's a bit confusing. :-) The value attribute defines the default value for the input, not its current value. It doesn't change when the user changes it. There is no attribute for the current value, you access it via the value property. Some attributes are reflected by properties with the same name (id, for instance), but value isn't one of them. (There is a property that reflects the value attribute: defaultValue. But again, it's the default, not the current value.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875