0

I have this:

$('.onealphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^a-zA-Z]/g{1},'') ); }
);

where what I hope it would do is that it allows the user to input only one letter in an input field. It accepts only letters for now, but I cannot make it to allow only one letter (and have searched dozens of SO answers). Any ideas?

Live demo

gsamaras
  • 71,951
  • 46
  • 188
  • 305

2 Answers2

1

Capture the first letter of the input and replace everything by its value.

$('.onealphaonly').bind('keyup', function() { 
    const node = $(this);
    node.val(node.val().replace(/^([a-zA-Z]).*/g, '$1'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="onealphaonly"/>
Erazihel
  • 7,295
  • 6
  • 30
  • 53
1

You have a syntax error in your regex. It should be formatted as /pattern/flags. Here is a regex that works: node.val().replace(/^([a-zA-Z])[a-zA-Z]+/g, '$1'). There are many ways of crafting a regex that'll do the job, however why don't you use the following instead:

node.val().substr(0, 1);

Also, you may have better success by also checking if the length of the value is greater than one and using e.preventDefault() like so:

if (node.val().length >= 1) {
    e.preventDefault();
    return false;
}

Fiddle: http://jsfiddle.net/ka52kdLv/14/

Adam Mazzarella
  • 763
  • 1
  • 7
  • 14