我在一些“用户名”字段中看到,您可以在其中输入用户名,然后在其下方,在类似于跨度的范围内,它将其附加到 url。很像我在底部的 StackOverflow 中输入时发生的事情。
我只想显示列表中允许的字符,忽略不在该列表中的任何字符输入。
我真的是 JS 新手。在这种情况下,我使用的是 Jquery,并且有一些部分可以工作,而其他部分我没有,或者我还没有到达那里。
愿望: 输入表单字段只接受列表中的字符,其他的将被忽略。 获取输入的新 key ,并将其附加到元素。
这是我目前遇到的乱七八糟的事情:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keyup(function(e) {
var entered = $('#cart-name').val();
entered = entered.toUpperCase();
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
// fromCharCode always returns uppercase?
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
var pos = allowed.indexOf(entered_char);
console.log('position is: ' + pos);
if (pos <= 0) {
console.log('does not contain');
} else {
console.log('contains');
}
$('#live').text(entered);
console.log(entered);
});
});
</script>
在我的 html 中:
<input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
<br />
http://example.com/
<span id="live"></span>
<br />
最佳答案
为什么不使用正则表达式来替换非字母数字字符?
entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');
关于javascript - 将输入限制为一组字符,同时显示这些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1391436/