Reputation: 444
I need to only allow letters to be typed, and I also need to capitalise the first letter of each word using javascript. I have the first bit working on keypress, I want the second working onblur, but I can't get it to work. It works ok if I use it on its own though. I've tried a bunch of things but I must be missing something small, I just can't figure out what it is.
HTML
<tr>
<td>
<input type="text" name="first_names" onkeypress="return isAlfa(event)" onblur="toTitleCase()">
</td>
<td>
<input type="text" name="last_names" onkeypress="return isAlfa(event)" onblur="toTitleCase()">
</td>
</tr>
JAVASCRIPT
function isAlfa(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
return false;
}
return true;
}
function toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
Please assist
Upvotes: 1
Views: 1500
Reputation: 193271
You need to reassign the value of the input, e.g. like onblur="this.value = toTitleCase(this.value)"
:
function isAlfa(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
return false;
}
return true;
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
<input type="text" name="first_names" onkeypress="return isAlfa(event)" onblur="this.value = toTitleCase(this.value)">
Upvotes: 5