0

I have a web app there is an input user can add some names in it but I don't want user to enter apostrophe ' sign. when user presses the ' sign html don't have to insert the character. I am new with html, also I have the js code file.

<div class="col-md-4">
    <input name="name" type="text"  class="form-control" placeholder="Name">
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Possible duplicate of [Easiest way to mask characters in HTML(5) text input](https://stackoverflow.com/questions/10887645/easiest-way-to-mask-characters-in-html5-text-input) – Rafael May 01 '19 at 07:50

3 Answers3

1

You can replace the character from the value with empty character. I will also recommend you to use some other name for the control as name is a keyword in JavaScript:

document.querySelector('[name=txtName]').addEventListener('input',function(){
    this.value = this.value.replace("'", '');
});
<div class="col-md-4">
  <input name="txtName" type="text"  class="form-control" placeholder="Name">
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Try this:

document.getElementById("input").onkeypress = function(e) {
    /^[a-zA-Z0-9]+$/.test(this.value)
};
<input type="text" id="input">

Change the regex to match the characters you want, currently only letters (lowercase and uppercase) and numbers.

Code from How to block special characters in HTML input field?

rainisr
  • 304
  • 3
  • 15
0
var digitsOnly = /[1234567890]/g;
var floatOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;

function restrictCharacters(myfield, e, restrictionType) {
    if (!e) var e = window.event
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    // if they pressed esc... remove focus from field...
    if (code==27) { this.blur(); return false; }
    // ignore if they are press other keys
    // strange because code: 39 is the down key AND ' key...
    // and DEL also equals .
    if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
        if (character.match(restrictionType)) {
            return true;
        } else {
            return false;
        }
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92