Nice programing

입력을 대문자로 변경

nicepro 2020. 11. 25. 21:09
반응형

입력을 대문자로 변경


JS :

<script type="text/css">
$(function() {
    $('#upper').keyup(function() {
        this.value = this.value.toUpperCase();
    });
});
</script>

HTML

<div id="search">
        <input type="radio" name="table" class="table" value="professor" tabindex="1" /> Professor
        <input type="radio" name="table" class="table" value="department" tabindex="2" /> Department
        <input type="radio" name="table" id="upper" class="table" value="course" tabindex="3" /> Course
        <input type="text" name="search" class="keywords" value="Select an option..." onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?':this.value;" tabindex="4"  />
        <div id="content"> </div>
    </div>

왜 여전히 작동하지 않습니까 ?? JS에서 div ".keywords"를 호출하려고합니다.


가장 우아한 방법은 자바 스크립트없이 CSS를 사용하는 것입니다. 사용할 수 있습니다 text-transform: uppercase(이것은 아이디어를위한 인라인입니다) :

<input id="yourid" style="text-transform: uppercase" type="text" />

편집하다:

따라서 귀하의 경우 키워드를 대문자로 변경하려면 다음 keywords: $(".keywords").val(),을 수행하십시오.$(".keywords").val().toUpperCase(),


자바 스크립트 문자열 객체에는 toLocaleUpperCase()변환 자체를 쉽게 하는 기능이 있습니다.

다음 은 실시간 대문자 사용 의 예 입니다.

$(function() {
    $('input').keyup(function() {
        this.value = this.value.toLocaleUpperCase();
    });
});

불행히도 이것은 텍스트 상자 내용을 완전히 재설정하므로 사용자의 캐럿 위치 ( "텍스트 상자의 끝"이 아닌 경우)가 손실됩니다.

그러나 브라우저 전환 마법을 사용하여 에서 다시 해킹 할 수 있습니다 .

// Thanks http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function getCaretPosition(ctrl) {
    var CaretPos = 0;    // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        CaretPos = ctrl.selectionStart;
    }

    return CaretPos;
}

function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}


// The real work

$(function() {
    $('input').keyup(function() {
        // Remember original caret position
        var caretPosition = getCaretPosition(this);

        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();

        // Reset caret position
        // (we ignore selection length, as typing deselects anyway)
        setCaretPosition(this, caretPosition);
    });
});

궁극적으로 속이는 것이 가장 쉬울 수 있습니다. text-transform: uppercase텍스트 상자에 스타일 설정하여 사용자에게 대문자로 표시 되도록 한 다음 사용자의 캐럿 포커스가 텍스트 상자를 완전히 벗어날 때마다 Javascript에서 텍스트 변환을 한 번 적용합니다.

HTML :

<input type="text" name="keywords" class="uppercase" />

CSS :

input.uppercase { text-transform: uppercase; }

자바 스크립트 :

$(function() {
    $('input').focusout(function() {
        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();
    });
});

도움이 되었기를 바랍니다.


이 방법으로도 할 수 있지만 다른 방법이 더 좋아 보이며 한 번만 필요한 경우 유용합니다.

onkeyup="this.value = this.value.toUpperCase();"

시험:

$('#search input.keywords').bind('change', function(){
    //this.value.toUpperCase();
    //EDIT: As  Mike Samuel suggested, this will be more appropriate for the job
    this.value = this.value.toLocaleUpperCase();
} );

html 입력 을 목적으로하는 경우 javascript를 사용하지 않고도 쉽게 수행 할 수 있습니다. 최신 CSS 태그는 표준이며 사용하기 매우 쉽습니다.

<input type="text" style="text-transform: uppercase" >

또는 "text-uppercase"라는 이름의 부트 스트랩 클래스를 사용할 수 있습니다.

<input type="text" class="text-uppercase" >

value.toUpperCase를 사용하는 솔루션은 필드에 텍스트를 입력하면 커서 위치가 텍스트의 끝으로 재설정되는 문제가있는 것 같습니다. 텍스트 변환을 사용하는 솔루션은 서버에 제출 된 텍스트가 여전히 잠재적으로 소문자라는 문제가있는 것 같습니다. 이 솔루션은 이러한 문제를 방지합니다.

function handleInput(e) {
   var ss = e.target.selectionStart;
   var se = e.target.selectionEnd;
   e.target.value = e.target.value.toUpperCase();
   e.target.selectionStart = ss;
   e.target.selectionEnd = se;
}
<input type="text" id="txtTest" oninput="handleInput(event)" />


답변 중 하나에서 언급 된 Bootstrap에서 텍스트 대문자를 찾을 수 없습니다. 아무리 만들었습니다.

.text-uppercase {
  text-transform: uppercase;
}

이렇게하면 텍스트가 대문자로 표시되지만 기본 데이터는 이러한 방식으로 변환되지 않습니다. 그래서 jquery에 있습니다.

$(".text-uppercase").keyup(function () {
    this.value = this.value.toLocaleUpperCase();
});

이렇게하면 text-uppercase 클래스를 사용할 때마다 기본 데이터가 변경됩니다.


onBlur="javascript:{this.value = this.value.toUpperCase(); }

대문자를 쉽게 바꿀 수 있습니다.

여기 데모


이 답변에는 문제가 있습니다.

style="text-transform: uppercase"

또한 자리 표시 자 단어를 불편한 대문자로 변환합니다.

placeholder="first name"

입력을 렌더링 할 때 "이름"자리 표시자를 대문자로 작성합니다.

FIRST NAME

그래서 더 나은 것을 썼습니다.

onkeypress="this.value = this.value + event.key.toUpperCase(); return false;"

it works good!, but it has some side effects if your javascript code is complex,

hope it helps somebody to give him/her an idea to develop a better solution.


Here we use onkeyup event in input field which triggered when the user releases a Key. And here we change our value to uppercase by toUpperCase() function.

Note that, text-transform="Uppercase" will only change the text in style. but not it's value. So,In order to change value, Use this inline code that will show as well as change the value

<input id="test-input" type="" name="" onkeyup="this.value = this.value.toUpperCase();">

Here is the code snippet that proved the value is change

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<form method="get" action="">
		<input id="test-input" type="" name="" onkeyup="this.value = this.value.toUpperCase();">
		<input type="button" name="" value="Submit" onclick="checking()">
	</form>
	<script type="text/javascript">
		function checking(argument) {
			// body...
			var x = document.getElementById("test-input").value
			alert(x);
		}
		
		
	</script>
</body>
</html>


<input id="name" data-upper type="text"/>
<input id="middle" data-upper type="text"/>
<input id="sur" data-upper type="text"/>

Upper the text on dynamically created element which has attribute upper and when keyup action happens

$(document.body).on('keyup', '[data-upper]', function toUpper() {
  this.value = this.value.toUpperCase();
});

**JAVA SCRIPT**
<html>
<body>
<script>
function @ToCaps(obj)
{
obj.value=obj.value.toUpperCase();
}
</script>
<input type="text" onkeyup=@ToCaps(this)"/>
</body>
</html>

**ASP.NET**
Use a css style on the text box, write css like this:

.ToCaps { text-transform: uppercase; }

<asp:TextBox ID="TextBox1" runat="server" CssClass="ToCaps"></asp:Te writxtBox>

**OR**
simply write this code in textbox
<asp:TextBox ID="TextBox1" runat="server" style="text-transform:uppercase"></asp:TextBox>


 **1.Note you don't get intelligence until you type up to style="**  

Javascript has a toUpperCase() method. http://www.w3schools.com/jsref/jsref_toUpperCase.asp

So wherever you think best to put it in your code, you would have to do something like

$(".keywords").val().toUpperCase()

you can try this HTML

<input id="pan" onkeyup="inUpper()" />

javaScript

function _( x ) {
  return document.getElementById( x );
}
  // convert text in upper case
  function inUpper() {
    _('pan').value = _('pan').value.toUpperCase();
  }

참고URL : https://stackoverflow.com/questions/5757101/change-input-to-upper-case

반응형