jQuery를 사용하여 사용자가 해당 필드를 편집하는 동안 텍스트 필드의 첫 글자를 어떻게 대문자로 표시합니까?
텍스트 필드에 입력되는 문자열의 첫 글자를 대문자로 표기하는 방법의 예를 찾고 있습니다. 일반적으로,이 함수, 정규 표현식으로 전체 필드에서 수행되고 OnBlur, OnChange사용자가있는 동안, 등 내가 첫 글자를 대문자로 할 여전히 입력합니다.
예를 들어 내가 "고양이"라는 단어를 입력하는 경우 사용자는 'c'를 누른 다음 'a'를 누를 때까지 필드에서 C를 대문자로 입력해야합니다.
나는 내가하려는 것이 keyup또는 로 가능할 것이라고 생각 keypress하지만 어디서부터 시작 해야할지 모르겠습니다.
누구든지 나를위한 모범이 있습니까?
CSS를 사용하십시오.
.myclass
{
text-transform:capitalize;
}
이것은 단순히 텍스트의 첫 글자를 변형시킵니다.
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
나는 이것을 다른 곳에서 대답했다. 그러나 여기에 keyup 이벤트에서 호출 할 수있는 두 가지 함수가 있습니다.
첫 단어를 대문자로하려면
function ucfirst(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
그리고 모든 단어를 대문자로
function ucwords(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
@Darrell이 제안한대로
$('input[type="text"]').keyup(function(evt){
// force: true to lower case all letter except first
var cp_value= ucfirst($(this).val(),true) ;
// to capitalize all words
//var cp_value= ucwords($(this).val(),true) ;
$(this).val(cp_value );
});
도움이 되었기를 바랍니다.
건배 :)
$('input[type="text"]').keyup(function(evt){
var txt = $(this).val();
// Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
$(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});
"text-transform : capitalize;"를 사용한 CSS 솔루션 백엔드에서 입력 내용을 사용하려는 경우 좋지 않습니다. 데이터는 그대로 수신됩니다. JavaScript는이 문제를 해결합니다.
앞에서 언급 한 몇 가지 기술을 결합한 JQuery 플러그인에 하이픈 뒤의 단어를 대문자로 표시합니다. 예 : "Tro Lo-Lo":
스크립트에 추가 :
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
return $word.toUpperCase();
}));
box.setSelectionRange(stringStart , stringEnd);
});
return this;
}
그런 다음 선택기에 capitalize ()를 연결하십시오.
$('#myform input').capitalize();
@Spajus 코드를 사용하고 더 확장 된 jQuery 플러그인을 작성했습니다.
다음 네 가지 jQuery 함수를 작성했습니다.
upperFirstAll()입력 필드의 모든 단어를 대문자로 표시upperFirst()FIRST 단어 만 대문자로upperCase()구멍 문자를 대문자로 변환하려면lowerCase()구멍 텍스트를 소문자로 변환하려면
다른 jQuery 함수처럼 사용하고 연결할 수 있습니다.
$('#firstname').upperFirstAll()
내 완전한 jQuery 플러그인 :
(function ($) {
$.fn.extend({
// With every keystroke capitalize first letter of ALL words in the text
upperFirstAll: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// With every keystroke capitalize first letter of the FIRST word in the text
upperFirst: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to lowercase
lowerCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase());
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to uppercase
upperCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toUpperCase());
box.setSelectionRange(start, end);
});
return this;
}
});
}(jQuery));
Groetjes :)
jQuery를 사용할 때 개인적으로 가장 좋아하는 것은 짧고 달콤합니다.
function capitalize(word) {
return $.camelCase("-" + word);
}
이 작업도 수행하는 jQuery 플러그인이 있습니다. 이름 : jCap.js
$.fn.extend($, {
capitalize: function() {
return $.camelCase("-"+arguments[0]);
}
});
$("#test").keyup(
function () {
this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
}
);
위의 코드를 약간 업데이트하여 첫 글자를 대문자로 표시하기 전에 문자열을 낮추십시오.
(둘 다 Jquery 구문 사용)
function CapitaliseFirstLetter(elemId) {
var txt = $("#" + elemId).val().toLowerCase();
$("#" + elemId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase(); }));
}
또한 전체 문자열을 대문자로 표시하는 기능 :
function CapitaliseAllText(elemId) {
var txt = $("#" + elemId).val();
$("#" + elemId).val(txt.toUpperCase());
}
텍스트 상자의 클릭 이벤트에 사용할 구문 :
onClick="CapitaliseFirstLetter('myTextboxId'); return false"
내 사과. 내가 서두르고 엉성했기 때문에 구문이 벗어났습니다. 여기 있습니다 ...
$('#tester').live("keyup", function (evt)
{
var txt = $(this).val();
txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
$(this).val(txt);
});
간단하지만 작동합니다. 당신은 이것을 더 일반적이고 플러그 앤 플레이 가능하게 만들고 싶을 것입니다. 이것은 더 적은 코드로 다른 아이디어를 제공하기위한 것입니다. 코딩에 대한 저의 철학은 가능한 한 일반적이고 가능한 한 적은 코드로 만드는 것입니다.
도움이 되었기를 바랍니다. 즐거운 코딩 되세요! :)
이걸로 입력 필드의 첫 글자 만 대문자로 쓸 수 있다는 게 정말 멋져요 .. 누군가 대문자로 바꾸는 방법을 알고 있다면 CSS text-transform : capitalize, Please Reply .. Here You go ..
$('input-field').keyup(function(event) { $(this).val(($(this).val().substr(0,1).toUpperCase())+($(this).val().substr(1))); });
터키 사람. 누군가가 여전히 관심이 있다면.
$('input[type="text"]').keyup(function() {
$(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])|\s+([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])/g, function ($1) {
if ($1 == "i")
return "İ";
else if ($1 == " i")
return " İ";
return $1.toUpperCase();
}));
});
이것은 당신을 도울 것입니다-각 단어의 첫 글자를 대문자로 변환
<script>
/* convert First Letter UpperCase */
$('#txtField').on('keyup', function (e) {
var txt = $(this).val();
$(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
return $1.toUpperCase( );
}));
});
</script>
예 : 이것은 타이틀 케이스 문장입니다-> 이것은 타이틀 케이스 문장입니다
로 자바 스크립트 당신은 사용할 수 있습니다 :
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
우연히 PHP로 웹 페이지를 생성하는 경우 다음을 사용할 수도 있습니다.
<?=ucfirst($your_text)?>
예외를 허용하는 솔루션 (매개 변수로 전달됨) :
아래 코드를 복사하여 다음과 같이 사용하십시오 : $ ( 'myselector'). maskOwnName ([ 'of', 'on', 'a', 'as', 'at', 'for', 'in', 'to ']);
(function($) {
$.fn.teste = function(not_capitalize) {
not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart,
end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = PHP.ucfirst(words[i]);
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
}
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
}
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
}
})(jQuery);
.first-character{
font-weight:bold;
color:#F00;
text-transform:capitalize;
}
.capital-text{
text-transform:uppercase;
}
Jquery or Javascipt doesn't provide a built-in method to achieve this.
CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.
If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>
var capitalizeString = function (word) {
word = word.toLowerCase();
if (word.indexOf(" ") != -1) { // passed param contains 1 + words
word = word.replace(/\s/g, "--");
var result = $.camelCase("-" + word);
return result.replace(/-/g, " ");
} else {
return $.camelCase("-" + word);
}
}
I use both CSS and jQuery solutions when achieving this. This will change both how it appears in the browser and the data value. A simple solution, that just works.
CSS
#field {
text-transform: capitalize;
}
jQuery
$('#field').keyup(function() {
var caps = jQuery('#field').val();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
jQuery('#field').val(caps);
});
My attempt.
Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names. Happens on Blur as to not cause annoyances on phones. Although left in selection start/end so if changed to keyup maybe useful still. Should work on phones but have not tried.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var lc = txt.toLocaleLowerCase();
var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
box.setSelectionRange(stringStart, stringEnd);
}
});
return this;
}
// Usage:
$('input[type=text].capitalize').capitalize();
Slight update to cumul's solution.
The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,
'program story' 카테고리의 다른 글
| 오류 : ': app : processDebugResources'작업에 대한 실행이 실패했습니다. (0) | 2020.11.22 |
|---|---|
| Core Graphics / Quartz 2D에서 둥근 사각형을 그리는 방법은 무엇입니까? (0) | 2020.11.22 |
| "train_test_split"메소드의 매개 변수 "stratify"(scikit Learn) (0) | 2020.11.22 |
| 쉼표 연산자를 언제 오버로드해야합니까? (0) | 2020.11.22 |
| NavigationView의 항목에 사용자 지정 서체를 설정하는 방법은 무엇입니까? (0) | 2020.11.22 |