클릭 시 HTML 텍스트 입력의 모든 텍스트 선택
HTML 웹 페이지에 텍스트 상자를 표시하는 코드는 다음과 같습니다.
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
페이지가 표시되면 Please enter the user ID 메시지가 텍스트에 포함되어 있습니다.그러나 모든 텍스트를 선택하려면 사용자가 3번 클릭해야 합니다(이 경우 사용자 ID를 입력하십시오).
원클릭만으로 전체 텍스트를 선택할 수 있습니까?
편집:
죄송합니다. 깜빡 말씀드리지 못했습니다. 입력은 사용하지 안 됩니다.type="text"
HTMlement에 JavaScript 메서드를 사용할 수 있습니다.
<label for="userid">User ID</label>
<input onClick="this.select();" value="Please enter the user ID" id="userid" />
하지만 모바일 사파리에서는 작동하지 않는 것 같아요.이 경우 다음을 사용할 수 있습니다.
<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" id="userid" />
이전에 게시된 솔루션에는 두 가지 특징이 있습니다.
- Chrome에서는 .select()를 통한 선택이 고정되지 않습니다.조금 타임아웃을 추가하면 이 문제가 해결됩니다.
- 초점을 맞춘 후 원하는 위치에 커서를 놓을 수 없습니다.
다음은 포커스에 맞는 모든 텍스트를 선택하지만 포커스에 맞는 특정 커서 포인트를 선택할 수 있는 완벽한 솔루션입니다.
$(function () {
var focusedElement;
$(document).on('focus', 'input', function () {
if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
focusedElement = this;
setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
});
});
Html (페이지에서 조작할 모든 입력에 onclick 속성을 붙여야 합니다)
<input type="text" value="click the input to select" onclick="this.select();"/>
또는 더 나은 옵션
jQuery(페이지의 모든 텍스트 입력에 대해 작동하며 html을 변경할 필요가 없습니다):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>
입력값의 예(더 이상)를 제공하기 위해 이 방법을 사용하면 안 됩니다.
가능한 경우 HTML 속성을 사용하는 것이 가장 좋습니다.
<label for="userid">User ID</label>
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
이렇게 하면 값을 입력하지 않으면 텍스트가 표시되므로 텍스트를 선택하거나 입력을 지울 필요가 없습니다.
플레이스 홀더는 텍스트를 입력하면 사라지며 접근성에 문제가 되므로 라벨을 대체할 수 없습니다.
하실 수 있습니다.document.execCommand
(모든 주요 브라우저에서 지원)
document.execCommand("selectall", null, false);
현재 포커싱된 요소의 모든 텍스트를 선택합니다.
2021: 데데 2021 2021 2021:execCommand
을 사용하다
다른 브라우저에 채택된 오래된 IE API로 작업하기엔 항상 조금 이상했기 때문에 솔직히 말하는 것이 최선일 것입니다.두 가지 효과가 이 하나 .<input>
및 " " "contenteditable
★★★★★★★★★★★★★★★★★★.
.select()
일 것이다<input>
요즘 밭에 있어요.
★★★의 contenteditable
최신 솔루션은 range API를 사용하는 것입니다.
주의: 검토 시onclick="this.select()"
첫 번째 클릭 시 [All characters](모든 문자)가 선택되고 그 후 입력된 내용을 편집하여 문자 사이를 다시 클릭할 수 있지만 모든 문자가 다시 선택됩니다.하려면 , 「」를 사용해 .onfocus
onclick
.
시험:
onclick="this.select()"
나한테는 잘 먹힌다.
나열된 답변은 제 생각에 일부입니다.Angular와 JQuery에서 이 작업을 수행하는 방법의 두 가지 예를 아래에 링크했습니다.
이 솔루션에는 다음과 같은 기능이 있습니다.
- JQuery, Safari, Chrome, IE, Firefox 등을 지원하는 모든 브라우저에서 작동합니다.
- Phonegap/Cordova: Android 및 IO에 대응합니다.
- 입력에 초점을 맞춘 후 다음 번 흐릿해질 때까지 한 번만 선택 후 포커스를 맞춥니다.
- 여러 입력을 사용할 수 있으며 글리치가 발생하지 않습니다.
- Angular Directive는 재사용이 용이합니다.단순히 디렉티브를 추가하여 클릭할 수 있습니다.
- JQuery는 쉽게 변경할 수 있습니다.
JQuery: http://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p=preview
$("input").blur(function() {
if ($(this).attr("data-selected-all")) {
//Remove atribute to allow select all again on focus
$(this).removeAttr("data-selected-all");
}
});
$("input").click(function() {
if (!$(this).attr("data-selected-all")) {
try {
$(this).selectionStart = 0;
$(this).selectionEnd = $(this).value.length + 1;
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
} catch (err) {
$(this).select();
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
}
}
});
각도: http://plnkr.co/edit/llcyAf?p=preview
var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var hasSelectedAll = false;
element.on('click', function($event) {
if (!hasSelectedAll) {
try {
//iOS, Safari, thows exception on Chrome etc
this.selectionStart = 0;
this.selectionEnd = this.value.length + 1;
hasSelectedAll = true;
} catch (err) {
//Non iOS option if not supported, e.g. Chrome
this.select();
hasSelectedAll = true;
}
}
});
//On blur reset hasSelectedAll to allow full select
element.on('blur', function($event) {
hasSelectedAll = false;
});
}
};
}]);
input autofocus, onfocus 이벤트 포함:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
이렇게 하면 원하는 요소를 선택한 상태에서 양식을 열 수 있습니다.자동 포커스를 사용하여 입력에 도달하면 자동으로 온포커스 이벤트가 전송되고 텍스트가 선택됩니다.
과연, 사용하다onclick="this.select();"
, 이 를 '이 명령어'와 주의해 주세요.disabled="disabled"
네, 선택해주세요. " " "와합니다.readonly
.
교환할 수 있습니다.
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
포함:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
플레이스 홀더는 사용자가 여러 번 클릭하거나 Ctrl + a를 사용하지 않고 텍스트 상자에 입력할 수 있는 방법으로 값을 대체하는 데 사용됩니다. 플레이스 홀더는 값이 아니라 이름이 플레이스 홀더를 시사하는 대로 값을 만듭니다.이는 "Username here" 또는 "Email"이라고 하는 여러 온라인 폼에서 사용되며, 클릭하면 "Email"이 사라지고 바로 입력을 시작할 수 있습니다.
CSS만의 솔루션을 찾고 있었는데 iOS 브라우저(Safari 및 Chrome 테스트 완료)에서 사용할 수 있다는 것을 알게 되었습니다.
데스크톱 크롬에서는 동일한 동작을 하지 않지만, 사용자만큼 다양한 옵션이 있기 때문에 선택하는 데 큰 어려움은 없습니다(두 번 클릭, ctrl+a 등).
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}
Showban의 재사용 가능한 답변은 다음과 같습니다.
<input type="text" id="userid" name="userid"
value="Please enter the user ID" onfocus="Clear(this);"
/>
function Clear(elem)
{
elem.value='';
}
이렇게 하면 여러 요소에 대해 클리어 스크립트를 재사용할 수 있습니다.
다음은 React의 예입니다만, 원하는 경우 바닐라 JS의 jQuery로 변환할 수 있습니다.
class Num extends React.Component {
click = ev => {
const el = ev.currentTarget;
if(document.activeElement !== el) {
setTimeout(() => {
el.select();
}, 0);
}
}
render() {
return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
}
}
여기서의 요령은onMouseDown
"click" 이벤트가 발생할 때까지 요소가 이미 포커스를 받았기 때문에activeElement
체크가 실패합니다).
그activeElement
체크는 사용자가 전체 입력을 지속적으로 다시 표시하지 않고 원하는 위치에 커서를 배치할 수 있도록 하기 위해 필요합니다.
그렇지 않으면 브라우저가 커서 위치 확인을 하기 때문에 텍스트가 선택되었다가 바로 선택 해제되기 때문에 타임아웃이 필요합니다.
그리고 마지막으로el = ev.currentTarget
는 React에서 필요합니다.React는 이벤트 객체를 재사용하기 때문에 setTimeout이 실행될 때까지 합성 이벤트가 손실됩니다.
이벤트를 통해 컨트롤하는 것이 좋다고 생각합니다.이 변형은 직관적으로 볼 수 있으며 ts에서도 작동합니다.
onFocus={e => {
e.target.select();
}
클릭할 때마다 모든 것을 선택해야 하는 경우 다음을 사용할 수 있습니다.
onClick={e => {
e.target.focus();
e.target.select();
}
문의하신 내용에 대한 정확한 해결책은 다음과 같습니다.
<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>
다만, 「사용자 ID 를 입력해 주세요」를 플레이스 홀더 또는 힌트로 표시하려고 하고 있는 것 같습니다.따라서 다음 사항을 보다 효율적인 솔루션으로 사용할 수 있습니다.
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
클릭 이벤트를 포착할 때의 문제는 텍스트 내에서 이후 클릭할 때마다 해당 이벤트가 다시 선택된다는 것입니다.이때 사용자는 커서 위치를 변경할 것으로 예상됩니다.
변수를 선언하고 SearchTextOnClick을 선택한 후 기본적으로 true로 설정했습니다.클릭 핸들러는 변수가 여전히 참인지 확인합니다.변수일 경우 변수를 false로 설정하고 select()를 수행합니다.그러면 흐릿한 이벤트 핸들러가 생성되어 다시 true로 설정됩니다.
지금까지의 결과는 내가 예상했던 행동처럼 보인다.
(편집: 누군가가 제안한 대로 포커스 이벤트를 잡아보려고 했지만 효과가 없습니다.포커스 이벤트가 발생한 후 클릭 이벤트가 발생하여 텍스트가 즉시 선택 취소됩니다.)
이 질문에는 .select()가 모바일플랫폼에서 동작하지 않는 경우의 옵션이 있습니다.iOS 디바이스(모바일 Safari)의 입력 필드의 텍스트를 프로그래밍 방식으로 선택합니다.
과 같은Html 。<input type="text" value="click the input to select" onclick="javascript:textSelector(this)"/>
바인드 없는 javascript 코드
function textSelector(ele){
$(ele).select();
}
이것은 TextBox의 정상적인 동작입니다.
1번 클릭 - 포커스 설정
2/3 클릭(두 번 클릭) - 텍스트 선택
페이지가 처음 로드될 때 TextBox에 포커스를 설정하여 "선택"을 더블 클릭 이벤트로 줄일 수 있습니다.
입력 필드에는 "value" 대신 "placeholder"를 사용합니다.
사용방법:
var textInput = document.querySelector("input");
textInput.onclick = function() {
textInput.selectionStart = 0;
textInput.selectionEnd = textInput.value.length;
}
<input type="text">
AngularJS를 사용하는 경우 쉽게 액세스할 수 있도록 사용자 지정 지시문을 사용할 수 있습니다.
define(['angular'], function () {
angular.module("selectionHelper", [])
.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
this.select();
});
}
};
});
});
이제 다음과 같이 사용할 수 있습니다.
<input type="text" select-on-click ... />
샘플에는 requiresjs가 포함되어 있으므로 다른 것을 사용하는 경우 첫 번째 줄과 마지막 줄을 건너뛸 수 있습니다.
jQuery(검색 필드에 적합한)를 사용하여 페이지 로딩으로 이 작업을 수행하고자 하는 사용자가 있다면 이 솔루션이 있습니다.
jQuery.fn.focusAndSelect = function() {
return this.each(function() {
$(this).focus();
if (this.setSelectionRange) {
var len = $(this).val().length * 2;
this.setSelectionRange(0, len);
} else {
$(this).val($(this).val());
}
this.scrollTop = 999999;
});
};
(function ($) {
$('#input').focusAndSelect();
})(jQuery);
이 투고에 근거합니다.CSS-Tricks.com 덕분에
했을 때 , "플레이스홀더 텍스트"를 사용하는 입니다.placeholder
때 하려면 @와 @이 가장합니다.그러나 필드가 포커스를 얻었을 때 현재 값을 모두 선택하려면 @Cory House와 @Toastrackenigma의 조합이 가장 표준적인 것으로 보입니다.focus
★★★★★★★★★★★★★★★★★」focusout
이벤트(현재 포커스 요소를 설정/해제하는 핸들러 포함)와 포커스된 경우 모두 선택합니다.단, 입니다). angular2/typescript는 angular2/typescript로 변환됩니다.
템플릿:
<input type="text" (focus)="focus()" (focusout)="focusout()" ... >
컴포넌트:
private focused = false;
public focusout = (): void => {
this.focused = false;
};
public focus = (): void => {
if(this.focused) return;
this.focused = true;
// Timeout for cross browser compatibility (Chrome)
setTimeout(() => { document.execCommand('selectall', null, false); });
};
순수 바닐라 javascript 메서드를 찾으시는 경우 다음 방법을 사용할 수도 있습니다.
document.createRange().selectNodeContents( element );
그러면 모든 텍스트가 선택되고 모든 주요 브라우저에서 지원됩니다.
포커스에 대한 선택을 트리거하려면 다음과 같이 이벤트청취자를 추가해야 합니다.
document.querySelector( element ).addEventListener( 'focusin', function () {
document.createRange().selectNodeContents( this );
} );
HTML 에 인라인으로 배치하는 경우는, 다음의 조작을 클릭합니다.
<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />
이건 또 다른 옵션일 뿐이야.몇 가지 방법이 있는 것 같습니다.(여기서 설명한 document.execCommand("selectall")도 마찬가지입니다.)
document.querySelector('#myElement1').addEventListener('focusin', function() {
document.createRange().selectNodeContents(this);
});
<p>Cicking inside field will not trigger the selection, but tabbing into the fields will.</p>
<label for="">JS File Example<label><br>
<input id="myElement1" value="This is some text" /><br>
<br>
<label for="">Inline example</label><br>
<input id="myElement2" value="This also is some text" onfocus="document.createRange().selectNodeContents( this );" />
「」를 사용합니다.placeholder="Please enter the user ID"
value="Please enter the user ID"
이 시나리오에서는 이 방법이 가장 좋지만 경우에 따라서는 이 기능이 도움이 될 수 있습니다.
<input>
""를 수 .focus
이벤트청취자는 이벤트청취자가 아니라 할 수 . 이벤트 청취자를 추가할 수 있습니다.document
click
.
플레인 JavaScript:
document.getElementById("userid").addEventListener("focus", function() {
this.select();
});
JQuery의 경우:
$("#userid").on("focus", function() {
this.select();
});
하면 .this.setSelectionRange(0, this.value.length)
this.select()
에 따라 , 이것은 .number
.
<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>
<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
$("#my_input").select();
});
//click to select and copy to clipboard
var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
var copy_text = document.getElementById("my_input_copy");
copy_text.focus();
copy_text.select();
try {
var works = document.execCommand('copy');
var msg = works ? 'Text copied!' : 'Could not copy!';
alert(msg);
} catch (err) {
alert('Sorry, could not copy');
}
});
</script>
언급URL : https://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked
'it-source' 카테고리의 다른 글
MYSQL: 특정 ID에 대한 다음 100개 및 이전 100개의 ID를 가져옵니다. (0) | 2023.01.13 |
---|---|
비동기 Javascript 함수를 동기적으로 호출 (0) | 2023.01.13 |
왜 2020년 3월 30일과 3월 1일의 차이가 29일이 아닌 28일을 잘못 제공하는가? (0) | 2023.01.13 |
Array.protype.reverse()를 사용하여 Vuejs v-for 무한 업데이트 루프 실행 (0) | 2023.01.13 |
외부 키 Larabel 오류가 있는 열 삭제: 일반 오류: 1025 이름 변경 시 오류 (0) | 2023.01.03 |