Daniel Yantis Daniel Yantis - 5 months ago 19
CSS Question

JavaScript toUpperCase only first letter

So again: I'm learning here!
Sorry for such basic questions but I've gotta learn...

Using a trick I read about online I'm trying to adapt it from cap all to cap first letters. See code here - specifically we are looking at the JavaScript

onkeyup
:

This works:

<label for="class">Classification</label>
<input type="text" name="class" id="class" value="" required="true" placeholder="" style="text-transform:uppercase" onkeyup="javascript:this.value=this.value.toUpperCase();" />


This does not work:

<label for="judge">Judge's Name</label>
<input type="text" name="judge" id="judge" value="" required="true" placeholder="" list="judges" style="text-transform:capitalize" onkeyup="javascript:this.value=this.charAt(0).toUpperCase() + this.substr(1);" />

Answer

You just missed to retrieve value property, you need to apply charAt and substr to a string not directly to the dom element.

<label for="judge">Judge's Name</label>
<input type="text" name="judge" id="judge" value="" required="true" placeholder="" list="judges" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />


FYI : Always it's better to use css, since there is option for capitalizing first letter(using text-transform:capitalize). Also instead of inline script code use a function, to make it more readable and easy to handle.


UPDATE : An another advice is to use Html5 input event instead of keyup which may be much better.

<label for="judge">Judge's Name</label>
<input type="text" name="judge" id="judge" value="" required="true" placeholder="" list="judges" style="text-transform:capitalize" oninput="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />


Also you can avoid the problem of moving arrow key(as @stdob commented) by adding an additional hidden input field with name judge and update value to that field and transfer it to the server.

function transform(ele) {
  var hid = document.getElementById('judge');
  hid.value =
    ele.value.charAt(0).toUpperCase() + ele.value.substr(1);
}
<label for="judge">Judge's Name</label>
<input type="text" value="" required="true" placeholder="" list="judges" style="text-transform:capitalize" onkeyup="transform(this)" />
<input type="hidden" name="judge" id="judge" value="" />