admin管理员组文章数量:1410697
I am looking for a simple maybe JS to forbid apostrophe onKeyUp or OnKeyPress kind of thing. For ex, every time user presses a key if it was apostrophe (Jame's Pizza) replace it with space. I don't want to process it in PHP
I found a code but it ties the JS to the textfield Name which I don't want. I need something global,
I am looking for a simple maybe JS to forbid apostrophe onKeyUp or OnKeyPress kind of thing. For ex, every time user presses a key if it was apostrophe (Jame's Pizza) replace it with space. I don't want to process it in PHP
I found a code but it ties the JS to the textfield Name which I don't want. I need something global,
- Show us the code you found, we can help you to adapt it. What do you mean by "something global"? – Bergi Commented Aug 17, 2012 at 15:03
- "I don't want to process it in PHP." You're going to need to process it in PHP as well since you can't trust user input. – Mike Samuel Commented Aug 17, 2012 at 15:11
2 Answers
Reset to default 7It's always better to prevent the keystroke than to retroactively delete it. To acplish this, you need to intercept the keypress
event (keyup
is too late):
document.getElementById('yourTextBoxID').onkeypress = function () {
if (event.keyCode === 39) { // apostrophe
// prevent the keypress
return false;
}
};
http://jsfiddle/TSB9r/
If you only want to stop the '
from appearing in the box but would like the keypress event to propagate to parent elements, replace the return false;
with event.preventDefault();
. (suggested by Eivind Eidheim Elseth in the ments)
Please find below functions. It grabs all of the input
elements on the page and assigns keydown
and keyup
event handlers to each of them. If they detect an apostrophe, it will call the preventDefault()
method..
function listen(event, elem, func) {
if (elem.addEventListener) return elem.addEventListener(event, func, false);
else elem.attachEvent('on' + event, func);
}
listen('load', window, function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
keyHandler(i);
}
function keyHandler(i) {
listen('keydown', inputs[i], function(e) {
if (e.keyCode === 222) { // 222 is the keyCode for apostrophe
e.preventDefault();
}
});
listen('keyup', inputs[i], function(e) {
if (e.keyCode === 222) { // 222 is the keyCode for apostrophe
e.preventDefault();
}
});
}
});
本文标签: javascriptForbidding Apostrophe while typing in HTML textBoxStack Overflow
版权声明:本文标题:javascript - Forbidding Apostrophe while typing in HTML textBox - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744320015a2600448.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论