阻止输入文本字段中的字符,将输入镜像到span或div [英] Block characters from input text field, mirror input into span or div

查看:80
本文介绍了阻止输入文本字段中的字符,将输入镜像到span或div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些html

<input type="text" name="name" value="" id="name">
<div id="preview"></div>

该字段的输入规则:

  • 在A-Z a-z 0-9字母之间加空格和破折号,不允许其他字符
  • 禁止输入任何字符

div的规则:

  • 显示在输入字段中输入的每个字符
  • 不显示禁止使用的字符
  • 遇到空格时,将其显示为破折号

我有各种各样的药水起作用,不起作用或行为异常.除了退格键/删除功能不起作用之外,此版本似乎在所有我可以测试的情况下均可正常工作.到目前为止仅在Safari中进行了测试.

I have had various potions working, not working, or misbehaving. This version seems to work in all cases I can test other than backspace/delete is non functional. Only tested in Safari so far.

还有其他陷阱"区域,例如在已经输入的文本之间输入文本,选择所有区域,使用箭头键,所有这些都在此问题中起作用.

There are other "gotcha" areas, like entering in text in-between already entered text, select all, using the arrow keys, all these play a role in this problem.

 $(document).ready(function(){
  $('#name').keypress(function(e) {
   // get key pressed
   var c = String.fromCharCode(e.which);
   // var d = e.keyCode? e.keyCode : e.charCode; // this seems to catch arrow and delete better than jQuery's way (e.which)
   // match against allowed set and fail if no match
   var allowed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ';
   if (e.which != 8 && allowed.indexOf(c) < 0) return false; // d !== 37 && d != 39 && d != 46 && 
   // just replace spaces in the preview
   window.setTimeout(function() {$('#preview').text($('#name').val().replace(/ /g, '-'));}, 1);
  });
 });

如果有办法在此职位上提供金钱上的赏金,请告诉我.是的,这就是我的位置:)

If there is a way to put a monetary bounty on this post, let me know. Yes, that is where I am at with this one :)

推荐答案

修补后,我重构了以前的解决方案.此版本的行为应与Twitter相同.我只是将旧答案保留下来,因为它在技术上是有效的,因此可以比较不同的方法.

After tinkering around I have refactored my previous solution. This version should behave identical to Twitter. I am keeping my old answer alive simply b/c it is technically valid, and this allows comparing the different approaches.

$(document).ready(function () {
    var SpacePattern = / /g;

    var name = $("#name");
    var preview = $("#preview");

    var updatePreview = function () {
        preview.text(name.val().replace(SpacePattern, "-"));
    };

    name.keypress(function (e) {
        if (e.which > 0 && // check that key code exists
            e.which != 8 && // allow backspace
            e.which != 32 && e.which != 45 && // allow space and dash
            !(e.which >= 48 && e.which <= 57) && // allow 0-9
            !(e.which >= 65 && e.which <= 90) && // allow A-Z
            !(e.which >= 97 && e.which <= 122)   // allow a-z
            ) {
            e.preventDefault();
        }
        else {
            setTimeout(updatePreview, 0);
        }
    });

    name.keyup(updatePreview); // Needed by IE for Delete and Backspace keys
});

这篇关于阻止输入文本字段中的字符,将输入镜像到span或div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆