To restrict commas in the textbox, handle the keypress event. If you are handling the keypress event using the onkeypress attribute, then inside the event handler function returns false when a user enters a comma.
The following JavaScript restrict a user from entering comma in the textbox:
function restrictComma(e){ if(e.keyCode === 44){ return false; }else{ return true; } }
Here is the HTML code for the textbox:
<input type="text" onkeypress="return restrictComma(event)" />
Note: The keyCode
property of the event
object returns 44 as the character code for the comma.
On the other hand, if you handle the keypress
event using the addEventListener()
method then call event.preventDefault()
method when a user enters a comma in the textbox.
let txt = document.getElementById("txtBox"); txt.addEventListener('keypress', e=>{ if(e.keyCode === 44){ e.preventDefault(); } });
HTML code for the textbox:
<input type="text" id="txtBox" />
You can also restrict commas in the textbox by handling the keydown
event.
Note: Inside the event handler of the keydown
event, the keyCode
property of the event object returns 188 for a comma.
function restrictComma(e){ if(e.keyCode === 188){ return false; }else{ return true; } } let txtBox = document.getElementById('txtBox'); txtBox.addEventListener('keydown', e=>{ if(e.keyCode === 188){ e.preventDefault(); } });
HTML code for the textbox:
<input type="text" onkeydown="return restrictComma(event)" /> <input type="text" id="txtBox" />