0

I have looked at answers to similar questions, but I still can't see why this code will not work:

function checkFname() {
  var fName = document.getElementById("firstName");
  var fnValue = fName.value;
  fnValue = fnValue.charAt(0).toUpperCase() + fnValue.slice(1);
  fName.innerHTML = fnValue;
  fName.style.backgroundColor = ((fnValue == "") ? "LightPink" : "#B0FFB0");
}
<div class="item">
  <label for="firstName"> First Name<span>*</span></label>
  <input id="firstName" type="text" name="firstName" onBlur="checkFname()" />
</div>

The function is called using onBlur in the field definition. fnValue gets capitalized correctly (evidenced by an alert box). The colour change in the field works fine if I leave the field blank.

It just doesn't want to replace the "all lower case" input with the capitalized version.

I have also tried document.getElementById("firstName").innerHTML in place of fName.innerHTML in the penultimate line above, but it makes no difference.

Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
PhilTilson
  • 55
  • 5

2 Answers2

1

Change fName.innerHTML = fnValue; to fName.value = fnValue;

Faris Han
  • 525
  • 3
  • 16
0

You probably want to update the value of the input instead of the innerHTML.

function checkFname() {
  var fName = document.getElementById("firstName");
  var fnValue = fName.value;
  fnValue = fnValue.charAt(0).toUpperCase() + fnValue.slice(1);
  fName.value = fnValue; // the change is here
  fName.style.backgroundColor = ((fnValue == "") ? "LightPink" : "#B0FFB0");
}
mwryl
  • 664
  • 7
  • 16