简体   繁体   中英

Allow only letters and spaces and capitalise each word

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

You need to reassign the value of the input, eg 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)"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM