Javascript 将输入框上的第一个字母转换为大写

Javascript 将输入框上的第一个字母转换为大写,javascript,jquery,Javascript,Jquery,这会将每个小写单词转换为大写。我有一个全名输入字段。我确实希望用户看到他/她按下的每个单词的第一个字母在输入字段中被转换为大写 $('input').on('keypress', function(event) { var $this = $(this), val = $this.val(), regex = /\b[a-z]/g; val = val.toLowerCase().replace(regex, function(letter) { ret

这会将每个小写单词转换为大写。我有一个全名输入字段。我确实希望用户看到他/她按下的每个单词的第一个字母在输入字段中被转换为大写

$('input').on('keypress', function(event) {
  var $this = $(this),
      val = $this.val(),
      regex = /\b[a-z]/g;

  val = val.toLowerCase().replace(regex, function(letter) {
    return letter.toUpperCase();
  });

  // I want this value to be in the input field.
  console.log(val);
});
我不知道如何正确替换当前输入字段中的选定字符

$('input').on('keypress', function(event) {
  var $this = $(this),
      val = $this.val(),
      regex = /\b[a-z]/g;

  val = val.toLowerCase().replace(regex, function(letter) {
    return letter.toUpperCase();
  });

  // I want this value to be in the input field.
  console.log(val);
});

例如:
const str=“hello world”
成为
hello world

const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);
或:

或:

简言之:

$this.val(val);


如图所示,这可以简化:

$(document).ready(function() {
    //alert('ready');

    $('input').on('keypress', function(event) {
        var $this = $(this),
            val = $this.val();

        val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
        $this.val(val);
    });
});

在我看来,另一种更好的解决方案是只将元素样式化为“存在”,然后在服务器端执行逻辑

这消除了任何javascript的开销,并确保在服务器端处理逻辑(无论如何都应该如此!)


使用会更好。

通过检查插入符号位置并重置插入符号位置,您可以将第一个字母转换为大写,同时避免光标跳到行首的恼人问题。我在表单上定义了几个函数,一个用于所有大写字母,一个用于正确的大写字母,一个仅用于初始大写字母。。。然后,插入符号位置有两个函数,一个用于获取,另一个用于设置:

function ProperCase(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g, 
          function($1) { return $1.toUpperCase(); });
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

function UpperCase(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.toUpperCase();
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

function initialCap(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.substr(0, 1).toUpperCase() + s.substr(1);
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

/* GETS CARET POSITION */
function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {

    el.value = el.value;

    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}
然后在文档准备就绪时,我将一个keyup事件侦听器应用于我想要检查的字段,但我只侦听可以实际修改字段内容的键(例如,我跳过“Shift”键…),如果用户点击“Esc”,我将恢复字段的原始值

  $('.updatablefield', $('#myform')).keyup(function(e) {
    myfield=this.id;
    myfieldname=this.name;
    el = document.getElementById(myfield);
    // or the jquery way:
    // el = $(this)[0];
      if (e.keyCode == 27) {                                 // if esc character is pressed
        $('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
        // if you only need to do the initial letter uppercase, you can apply it here directly like this:
        initialCap(el);
      }                                                    // end if (e.keyCode == 27)
      // if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
      else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
        // if you only need to do the initial letter uppercase, you can apply it here directly like this:
        initialCap(el);
      } // end else = if any other character is pressed                      //
  }); // end $(document).keyup(function(e)
$('.updateablefield',$('#myform')).keyup(函数(e){
myfield=this.id;
myfieldname=this.name;
el=document.getElementById(myfield);
//或者jquery方式:
//el=$(本)[0];
如果(e.keyCode==27){//如果按下esc字符
$(“#”+myfield).val(原始#field_值[myfield])//我将字段的原始值存储在数组中。。。
//如果您只需要使用大写字母的首字母,您可以在此处直接使用它,如下所示:
首字母大写(el);
}//如果(e.keyCode==27)结束
//如果按下将修改字段的任何其他字符(字母、数字、符号、空格、退格、del…)
如果(e.keyCode==8 | e.keyCode==32 | e.keyCode>45&&e.keyCode<91 | e.keyCode>95&&e.keyCode<112 | e.keyCode>185&&e.keyCode<223 | e.keyCode==226){
//如果您只需要使用大写字母的首字母,您可以在此处直接使用它,如下所示:
首字母大写(el);
}//end else=如果按下任何其他字符//
}); // 结束$(文档).keyup(函数(e)

您可以在这里看到这个示例的一个可用小提琴:

这将适用于keyup上的每个textfield调用函数

其中id是textfield的id,value是您在textfield中键入的值

function capitalizeFirstLetter(value,id)
{

    if(value.length>0){

        var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
        document.getElementById(id).value=str;

    }

}

仅使用此此作品的首字母大写

style="text-transform:capitalize;



您可以将css用于输入元素文本转换:大写;@Dineshkani值得注意的是,这不会应用于表单提交,但这只是一种样式更改。我通常会这样做?更改
按键上的值会让用户感到恼火,因为它会不断将光标移动到框的末尾,即使它们变为bac改为“代码>更改<代码> >。我更新了AdENOO的解决方案,以解决@ N布鲁克关注点:使用-这是一个干净的实时解决方案,让用户知道它立即被资本化,而不是模糊或某事。LeL,我现在觉得很笨。应该休息一下。st输入字段中的第一个字母这不会影响基础值,只会影响它的显示方式。此答案不提供您这样做的原因和内容。请提供更多信息,提前感谢!mystring'[0]。toUpperCase()+'mystring'.substr(1)
function ProperCase(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g, 
          function($1) { return $1.toUpperCase(); });
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

function UpperCase(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.toUpperCase();
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

function initialCap(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.substr(0, 1).toUpperCase() + s.substr(1);
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

/* GETS CARET POSITION */
function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {

    el.value = el.value;

    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}
  $('.updatablefield', $('#myform')).keyup(function(e) {
    myfield=this.id;
    myfieldname=this.name;
    el = document.getElementById(myfield);
    // or the jquery way:
    // el = $(this)[0];
      if (e.keyCode == 27) {                                 // if esc character is pressed
        $('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
        // if you only need to do the initial letter uppercase, you can apply it here directly like this:
        initialCap(el);
      }                                                    // end if (e.keyCode == 27)
      // if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
      else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
        // if you only need to do the initial letter uppercase, you can apply it here directly like this:
        initialCap(el);
      } // end else = if any other character is pressed                      //
  }); // end $(document).keyup(function(e)
function capitalizeFirstLetter(value,id)
{

    if(value.length>0){

        var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
        document.getElementById(id).value=str;

    }

}
style="text-transform:capitalize;
<asp:TextBox ID="txtName" style="text-transform:capitalize;" runat="server" placeholder="Your Name" required=""></asp:TextBox>
   $('.form-capitalize').keyup(function(event) {
        var $this = $(this),
        val = $this.val(),
        regex = /\b[a-z]/g;
        val = val.toLowerCase().replace(regex, function(letter) {
            return letter.toUpperCase();
        });
        this.value = val;
        // I want this value to be in the input field.
      console.log(val);
    });