用于大写文本输入的JavaScript代码

我正在使用流行的Firefox扩展Greasemonkey.

我想知道是否有办法以某种形式大写所有文本输入,所以如果我使用jQuery代码看起来像:

$('form#formid input[type=text]').capitalize();

当然我知道.capitalize()不是一个有效的函数,为了大写文本你需要一个复杂的JavaScript代码,但毕竟谷歌搜索,我找不到一个似乎可以实现到Greasemonkey .

任何人都可以帮我写这个脚本吗?

通过大写,我的意思是大写每个单词的第一个字母,如CSS text-transform:capitalize;并且它必须覆盖用户可能放入的字母,也许在表单提交上更容易…

谢谢.

解决方法

//add a function to jQuery so we can call it on our jQuery collections
$.fn.capitalize = function () {

    //iterate through each of the elements passed in,`$.each()` is faster than `.each()
    $.each(this,function () {

        //split the value of this input by the spaces
        var split = this.value.split(' ');

        //iterate through each of the "words" and capitalize them
        for (var i = 0,len = split.length; i < len; i++) {
            split[i] = split[i].charat(0).toupperCase() + split[i].slice(1);
        }

        //re-join the string and set the value of the element
        this.value = split.join(' ');
    });
    return this;
};

这是一个演示:http://jsfiddle.net/jasper/qppGQ/1/

这可以在事件处理程序中使用,以始终保持大写的文本体:

//when the user presses a key and the value of the `textarea` is changed,the new value will have all capitalized words
$('textarea').on('keyup',function () {
    $(this).capitalize();
}).capitalize();//also capitalize the `textarea` element(s) on initialization

这是一个演示:http://jsfiddle.net/jasper/qppGQ/2/

更新

要使第一个字母大写,并且单词的其余部分为小写,我们可以在大写第一个字母后在字符串的其余部分中使用.toLowerCase():

...
        for (var i = 0,len = split.length; i < len; i++) {
            split[i] = split[i].charat(0).toupperCase() + split[i].slice(1).toLowerCase();
        }
        ...

这是一个演示:http://jsfiddle.net/jasper/qppGQ/3/

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...