-1

Would someone be able to help me with some javascript code please that will alert on submission of a form if there's a ' character (apostrophe) within a textbox?

Thank you.

Philip
  • 2,460
  • 4
  • 27
  • 52

2 Answers2

0

You can use String.prototype.indexOf to check for apostrophe's presence:

var str = "That's awesome";
if(str.indexOf("'") !== -1) {
    alert("no apostrophe's allowed");
}

Doing it on form submission is a separate issue.

hon2a
  • 7,006
  • 5
  • 41
  • 55
dan-klasson
  • 13,734
  • 14
  • 63
  • 101
0

Add keyUp event listener to the textbox. Check the keyCode of the key pressed. If it matched for keyCode of ', alert the user. After that, replace the ' with a blank.

document.getElementById('input').addEventListener('keyup', function(e){
  if(e.keyCode === 222){ // check if the key pressed is '
    alert('No Single Quotes Please!');
    this.value = this.value.replace("'", "");  // replace ' with a blank
  }
}, false);
<input type="text" id="input" />

Readup on these:

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138