Javascript 使用javascript将用户类型转换为大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5571514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:51:52  来源:igfitidea点击:

Convert to uppercase as user types using javascript

javascriptjqueryuppercasekeycode

提问by Butcher

I want to convert lowercase chars to uppercase as the user types using javascript. Any suggestions are welcome.

当用户使用 javascript 键入时,我想将小写字符转换为大写字符。欢迎任何建议。

I have tried the following:

我尝试了以下方法:

$("#textbox").live('keypress', function (e) {
    if (e.which >= 97 && e.which <= 122) {
        var newKey = e.which - 32;
        // I have tried setting those
        e.keyCode = newKey;
        e.charCode = newKey;
    }
});

采纳答案by Shaz

$("#textbox").bind('keyup', function (e) {
    if (e.which >= 97 && e.which <= 122) {
        var newKey = e.which - 32;
        // I have tried setting those
        e.keyCode = newKey;
        e.charCode = newKey;
    }

    $("#textbox").val(($("#textbox").val()).toUpperCase());
});

回答by kennebec

css

#textbox{text-transform:uppercase}

回答by Andres SK

This might be a nice workaround. Just set this in your CSS:

这可能是一个不错的解决方法。只需在您的 CSS 中设置它:

input#textbox {
    text-transform: uppercase;
}

If you post the data to a server side script (lets say php) you can always do something like this:

如果您将数据发布到服务器端脚本(比如 php),您可以随时执行以下操作:

$upper_data = strtoupper($_POST['textbox']);

回答by Yann86

Hi this code works fine on input and textarea without delay or capitalization change

嗨,这段代码在 input 和 textarea 上工作正常,没有延迟或大小写变化

$("#input").on('input', function(evt) {
              var input = $(this);
              var start = input[0].selectionStart;
              $(this).val(function (_, val) {
                return val.toUpperCase();
              });
              input[0].selectionStart = input[0].selectionEnd = start;
            });

mix from https://stackoverflow.com/a/7944108/1272540and https://stackoverflow.com/a/13155583/1272540

混合来自https://stackoverflow.com/a/7944108/1272540https://stackoverflow.com/a/13155583/1272540

jsFiddle

js小提琴

回答by percayahati

try this css script it's work for me.

试试这个 css 脚本,它对我有用。

<style>    
input{text-transform:uppercase};
</style>    

for information, what you see maybe upper case but it's actually still what you type like if you type "Test" it shown as "TEST" but when your get by val() it shown as "Test".

有关信息,您看到的可能是大写,但实际上仍然是您键入的内容,如果您键入“Test”,它会显示为“TEST”,但是当您通过 val() 获取时,它会显示为“Test”。

if you want to make it be upper case for real then add some script below on event like blur from the object or elenent as you need.

如果你想让它成为真实的大写,然后根据需要在下面添加一些脚本,例如来自对象的模糊或元素。

$(this).val($(this).val().toUpperCase());

$(this).val($(this).val().toUpperCase());

And if you want to use for specific object add some extra script like what i used by now

如果您想用于特定对象,请添加一些额外的脚本,例如我现在使用的

input[attr]{
text-transform:uppercase;
}

input[attr='value']{
text-transform:uppercase;
}

回答by T rakesh

$(document).ready(function () {
        $("#textbox").keyup( function (e) {
            var str = $(this).val();
            $("#textbox").val(str.toUpperCase());
});
});

回答by Chris HG

I know I'm quite late to the party, but I'd like to offer this:

我知道我参加聚会已经很晚了,但我想提供以下信息:

(function ( $ ) {

  var displayUppercase = function ($element) {
    if ($element.val()) {
      $element.css('text-transform', 'uppercase');
    } else {
      $element.css('text-transform', 'none');
    }
  };

  $.fn.displayAsUppercase = function() {
    $(this).each(function() {
        var $element = $(this);
      displayUppercase($element);
      $element.on('input', function(){displayUppercase($element)});
    });
    return this;
    };

}( jQuery ));

It has these advantages:

它具有以下优点:

  • Keeps the placeholder capitalization intact
  • Capitalizes the input immediately (on keydown)
  • Doesn't move the cursor
  • Capitalizes the value of the input if it's prepopulated
  • 保持占位符大小写不变
  • 立即将输入大写(在 keydown 上)
  • 不移动光标
  • 如果输入的值已预先填充,则将其大写

JS Fiddle here

JS小提琴在这里

回答by Vishrant

function changeToUpperCase(event,obj) {
    charValue = (document.all) ? event.keyCode : event.which;
    if (charValue!="8" && charValue!="0" && charValue != "27"){
        obj.value += String.fromCharCode(charValue).toUpperCase();
        return false;
    }else{
        return true;
    }
}

<input id="txtId" type="text" onkeypress="return changeToUpperCase(event,this)" />

Edit:

编辑:

The most simplest wayis by using css:

简单的方法是使用css:

#txtId {text-transform:uppercase}

回答by BobRodes

Since you tagged this as a jQuery question as well, here's a simple (well, fairly simple) jQuery solution:

由于您也将此标记为 jQuery 问题,因此这里有一个简单(好吧,相当简单)的 jQuery 解决方案:

$('#text_statute_section').on('keypress', function(event) {
    if(null !== String.fromCharCode(event.which).match(/[a-z]/g)) {
        event.preventDefault();
        $(this).val($(this).val() + String.fromCharCode(event.which).toUpperCase());
    }
});

Using keypress prevents the "bounce" effect that keyup has (keydown also does, but event.which doesn't distinguish directly between upper and lower case here--shift key check is messy owing to caps lock). Also, this operates on the input character, converts it to uppercase, and then appends it to the existing value, rather than first appending and then converting the whole thing to uppercase as most of the other solutions I've seen do. Finally, it actually converts the character rather than applying a formatting style to it as CSS does. All this gives better control, especially in situations where some characters need to be forced to uppercase and some not, such as in serial numbers or the like.

使用 keypress 可以防止 keyup 具有的“弹跳”效果(keydown 也可以,但是 event.which 不直接区分大小写在这里 - 由于大写锁定,shift 键检查很混乱)。此外,这对输入字符进行操作,将其转换为大写,然后将其附加到现有值,而不是像我见过的大多数其他解决方案那样首先附加然后将整个内容转换为大写。最后,它实际上转换了字符,而不是像 CSS 那样对其应用格式样式。所有这些都提供了更好的控制,尤其是在某些字符需要强制为大写而另一些不需要的情况下,例如在序列号等中。

EDIT: (four years later)!

编辑:(四年后)!

I've never been happy with how jQuery/javascript handles changing keys to uppercase as they are typed in. I've been over all the suggestions in this post, and none of them (least of all mine) quite work flawlessly. This is irritating to me, as it was a simple matter in the old VB6 days to change the KeyAscii character that was passed to the KeyPress event. Anyway, quite by accident, I have found a sort of "black art" solution that does work flawlessly as far as I have tested it. Meaning it works in Chrome, it correctly handles any cursor position on the text, it (with some work) doesn't change the browser's focus behavior, and it reliably changes to uppercase without any sort of jittery showing of lowercase first. While the CSS solution also does all of this, as others have observed it has the drawback of having to programmatically force the underlying characters to uppercase when you need the actual string to work with, which can be a hassle to keep track of and therefore doesn't scale well. So, I thought I might write this up, in case someone finds it useful.

我从来没有对 jQuery/javascript 如何在键入时处理将键更改为大写感到满意。我已经阅读了这篇文章中的所有建议,但没有一个(至少是我的)完美地工作。这让我很恼火,因为在旧的 VB6 时代,更改传递给 KeyPress 事件的 KeyAscii 字符是一件简单的事情。无论如何,很偶然地,我发现了一种“黑色艺术”解决方案,据我对其进行测试,它确实可以完美运行。这意味着它在 Chrome 中工作,它可以正确处理文本上的任何光标位置,它(通过一些工作)不会改变浏览器的焦点行为,并且它可靠地更改为大写,而不会首先显示任何小写字母。虽然 CSS 解决方案也完成了所有这些,正如其他人所观察到的那样,它有一个缺点,即当您需要使用实际字符串时,必须以编程方式强制底层字符为大写,这可能很难跟踪,因此不能很好地扩展。所以,我想我可以把它写下来,以防有人觉得它有用。

This solution does depend on Josh Bush's little (180 lines of code, for those worried about dependency bloat) Masked Input Plugin from digitalbush, which is rock solid and does what it does very well. If you change event.whichto another value, and call the mask()method afterwards (specify the keypress handler first and the mask second in your code) the change will persist.

这个解决方案确实依赖于 Josh Bush 的小(180 行代码,对于那些担心依赖膨胀的人)来自 digitalbush 的 Masked Input Plugin,它坚如磐石,并且做得很好。如果更改event.which为另一个值,然后调用该mask()方法(在代码中首先指定按键处理程序,然后指定掩码),更改将持续存在。

Here's a bit of code:

这是一些代码:

$.mask.definitions['b'] = '[A-Z, ]';

$('#txtMyInput').on('keypress', function(e) {
    e.which =     String.fromCharCode(e.which).toUpperCase().charCodeAt(0);
})
.mask('b?bbbbbbbbbbbbbbbbbbb', { placeholder: '' })

Mask doesn't support very many mask types natively: literals, alpha, numeric and alphanumeric are it. If you want punctuation or whatever you have to roll your own using regex. (If you do this, you'll need to keep in mind that the same regex match is applied to each character one at a time, without consideration of the other characters, so you can't do anything fancy). In my particular case, I needed all caps, plus spaces and commas. The ?in the mask string means the following characters are optional, so this one gives me up to 20 characters. Since I didn't need any mask to show, I used an empty string for a placeholder.

掩码本身并不支持很多掩码类型:文字、字母、数字和字母数字都是它。如果你想要标点符号或任何你必须使用正则表达式自己滚动的东西。(如果你这样做,你需要记住,相同的正则表达式匹配一次应用于每个字符,不考虑其他字符,所以你不能做任何花哨的事情)。在我的特殊情况下,我需要全部大写,加上空格和逗号。将?在掩码字符串表示下列字符是可选的,所以这一块给了我最多20个字符。由于我不需要任何掩码来显示,我使用了一个空字符串作为占位符。

That all works perfectly, except for the one small problem: if you want to keep the way the browser selects the text when tabbing into the field, you have to do extra work. I wound up having to hack the mask code to get what I wanted.

一切都很完美,除了一个小问题:如果你想在用 Tab 键进入字段时保持浏览器选择文本的方式,你必须做额外的工作。我最终不得不破解掩码代码才能得到我想要的东西。

I first tried simply selecting the text in a focus event handler, which normally works when I call focus()from a keydown handler. It didn't work here; the cursor just got set to the end of the text as it would on a mouse click there. I tried changing the placeholder to a space. This resulted in padding the text with enough spaces to fill up the limit specified, and selecting the whole thing.

我首先尝试在焦点事件处理程序中简单地选择文本,这通常在我focus()从 keydown 处理程序调用时起作用。它在这里不起作用;光标刚刚设置到文本的末尾,就像在那里单击鼠标一样。我尝试将占位符更改为空格。这导致用足够的空间填充文本以填充指定的限制,并选择整个内容。

I tried some of the techniques here, but the best of them (i.e. the one that actually worked in this case) still doesn't apply the highlight until key up, which means there's a lag in when it happens, and it doesn't happen at all if you hold the key down till it repeats and happen to let go when the focus is in the box.

我在这里尝试了一些技术,但其中最好的(即在这种情况下实际有效的技术)在按键之前仍然不会应用高光,这意味着它发生时会有延迟,并且它不会如果您按住键直到它重复并在焦点位于框中时碰巧放开,则根本不会发生。

So I dug into the mask code. As it turns out, the plugin also has a focus event handler that it uses to set up the mask indicator (say, (___) ___-___-____for a phone) in the box when you focus on it. This is the behavior you want most of the time, but not here, because it replaces the selected text with the selected text concatenated to the part of the mask indicator that hasn't been filled yet. When you don't have a mask indicator, this has the effect of deselecting the text in the box just as would happen if you programmatically assigned the text value of the box.

所以我挖掘了掩码代码。事实证明,该插件还有一个焦点事件处理程序,(___) ___-___-____用于在您聚焦时在框中设置遮罩指示器(例如,用于电话)。这是您大多数时候想要的行为,但在这里不是,因为它将所选文本替换为连接到尚未填充的遮罩指示器部分的所选文本。当您没有蒙版指示器时,这会产生取消选择框中文本的效果,就像您以编程方式分配框的文本值一样。

I decided to hack the mask code a bit. I first tried commenting out the entire focus event handler, which had the effect of not showing the input mask on other fields where I wanted it. So, I found a less invasive alternative. I changed this (currently jquery.maskedinput.js, line 164):

我决定稍微修改一下掩码代码。我首先尝试注释掉整个焦点事件处理程序,这会导致在我想要的其他字段上不显示输入掩码。所以,我找到了一种侵入性较小的替代方案。我改变了这个(目前是 jquery.maskedinput.js,第 164 行):

}).on("focus.mask", function() {
    if (!input.prop("readonly") { 
        // etc.

to this:

对此:

}).on("focus.mask", function() {
    if (!input.prop("readonly") && settings.placeholder.length > 0) {

This bypasses setting up the mask indicator if you have set your placeholder to a blank string, which allows the browser's native focus behavior to take place.

如果您将占位符设置为空白字符串,这将绕过设置掩码指示器,这允许浏览器的本机焦点行为发生。

One more thing: if you are using the focus()method to focus on the text box (for example, to rescue the data entry user from the browser's tendency to wander to parts unknown upon use of the tab key), you'll have to call the select()method in the focus event handler to properly highlight the text (keybdFocusis a flag I set when I call the focus()event from a keydownhandler, so as to distinguish from a mouse-generated focus):

还有一件事:如果您使用该focus()方法专注于文本框(例如,为了使数据输入用户免于浏览器在使用 Tab 键时徘徊到未知部分的倾向),则必须调用select()焦点事件处理程序中正确突出显示文本的方法(这keybdFocus是我在focus()keydown处理程序调用事件时设置的标志,以便与鼠标生成的焦点区分开来):

$('#txtMyInput').on('keypress', function(e) {
    e.which = String.fromCharCode(e.which).toUpperCase().charCodeAt(0);
})
.mask('b?bbbbbbbbbbbbbbbbbbb', { placeholder: '' })
.focus(function() {
    if (kybdFocus) {
        kybdFocus = false;
        $(this).select();
    }
});

Summarizing the steps:

总结步骤:

  1. Download Josh Bush's Masked Edit Plugin.
  2. Change the line of code in the plugin's focus handler.
  3. Set up a mask definition (if needed) to handle the characters you want.
  4. In your keypress event handler, use your favorite technique to change e.which to its uppercase equivalent. (Important: the call to the handler must precedethe call to the mask()method in your code. The mask evaluates e.which to determine whether the candidate character fits the mask, and apparently the handler and the mask code are fired in the order in which they are specified.)
  5. Set the placeholder value to ''when you call the mask()method.
  6. If you hit the input box with a focus, call the select()method in your focus event handler.
  1. 下载 Josh Bush 的 Masked Edit 插件。
  2. 更改插件的焦点处理程序中的代码行。
  3. 设置掩码定义(如果需要)来处理您想要的字符。
  4. 在您的按键事件处理程序中,使用您最喜欢的技术将 e.which 更改为大写的等效项。(重要:对处理程序的调用必须mask()在您的代码中调用方法之前。掩码评估 e.which 以确定候选字符是否适合掩码,显然处理程序和掩码代码按以下顺序触发它们被指定。)
  5. ''调用mask()方法时将占位符值设置为。
  6. 如果您使用焦点点击输入框,请select()在您的焦点事件处理程序中调用该方法。

Of course, if you just want to force characters to uppercase in the context of a typical masked edit box, you can omit steps 2 and 4. That's how I fell into this in the first place.

当然,如果您只是想在典型的屏蔽编辑框的上下文中强制字符为大写,则可以省略第 2 步和第 4 步。这就是我最初陷入困境的原因。

回答by garryp

This is a solution I came up with, which also avoids the issues with placeholders changing to upper case, and does not mess around with the cursor position.

这是我想出的一个解决方案,它也避免了占位符更改为大写的问题,并且不会弄乱光标位置。

Caution: does not change the "value" of the field, only the display. For that see here: Updating an input's value without losing cursor position

注意:不改变字段的“值”,只改变显示。为此,请参见此处:在不丢失光标位置的情况下更新输入值

$(function() {
    $("[data-uppercase='1']").on('keypress', function (e) {
        var $this = $(this);
        var placeholder = $this.attr('placeholder');
        if(placeholder && placeholder.length > 0) {
            this["_placeholder"] = placeholder;
            $this.attr('placeholder', '');
        }
        $this.css('text-transform', 'uppercase');
    }).on('keyup blur', function () {
        var $this = $(this);
        if ($this.val().length < 1) {
            $this.css("text-transform", "");
            $this.attr("placeholder", this["_placeholder"]);
            this["_placeholder"] = undefined;
        }
    });
});

Then add a data-uppercase attribute to the HTML element:

然后给 HTML 元素添加一个 data-uppercase 属性:

<input type="text" data-uppercase="1" />

Worked in Chrome, Firefox and IE9+.

曾在 Chrome、Firefox 和 IE9+ 中工作。

Fiddle: https://jsfiddle.net/GarryPas/ptez7q0q/3/

小提琴:https: //jsfiddle.net/GarryPas/ptez7q0q/3/