I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^). Can any one tell me how to restrict uparrow(^) ?
function onlyAlphabet(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var keychar = String.fromCharCode(key);
var keycheck = /[a-zA-z\s]/;
if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete escape arrows
{
if (!keycheck.test(keychar)) {
theEvent.returnValue = false;//for IE
if (theEvent.preventDefault)
theEvent.preventDefault();//Firefox
}
}
}
html code
<div class="form-group">
<label class="form-text">Travels Name</label>
<h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />
</div>
You can achieve that in a more simpler way like the following:
function onlyAlphabet(inputVal) {
var patt=/^[a-zA-Z]+$/;
if(patt.test(inputVal)){
document.getElementById('txtTravel').value = inputVal;
}
else{
var txt = inputVal.slice(0, -1);
document.getElementById('txtTravel').value = txt;
}
}
<div class="form-group">
<label class="form-text">Travels Name</label>
<input id="txtTravel" type="text" maxlength="50"
oninput="onlyAlphabet(value)" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With