클릭 후 입력 텍스트를 지우려면 어떻게 해야 합니까?
jQuery를 사용하여 클릭 후 입력된 텍스트를 지우려면 어떻게 해야 합니까?기본적으로 값은 입력 필드에 남아 있습니다.
예를 들어, 나는 입력 텍스트를 가지고 있고 그 값은TEXT
. 클릭을 수행할 때 입력 필드가 비어 있으면 합니다.
기본 텍스트를 제거하려면 요소를 클릭할 때:
$('input:text').click(
function(){
$(this).val('');
});
하지만, 저는 제가 제안하고 싶은 것은focus()
대신:
$('input:text').focus(
function(){
$(this).val('');
});
키보드 이벤트(예: 탭 키)에도 응답합니다.또한, 당신은 사용할 수 있습니다.placeholder
요소의 속성:
<input type="text" placeholder="default text" />
요소의 초점이 지워지고 요소가 빈 상태로 남아 있거나 사용자가 아무것도 입력하지 않으면 다시 나타납니다.
업데이트: "클릭"이라는 말을 문자 그대로 받아들였는데, 저는 좀 어이가 없었습니다.대체가능합니다focus
위해서click
사용자가 입력을 탭할 때도 작업이 수행되도록 하려면 아래의 모든 항목을 참조하십시오.
업데이트 2: 제 생각에는 플레이스홀더를 하려고 하는 것 같습니다. 메모와 예제는 마지막에 참조하십시오.
원래 답변:
다음을 수행할 수 있습니다.
$("selector_for_the_input").click(function() {
this.value = '';
});
...하지만 그것이 무엇이든 간에 텍스트를 지워줄 것입니다.특정 값인 경우에만 지우기를 원하는 경우:
$("selector_for_the_input").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
예를 들어, 입력에 다음과 같은 정보가 있는 경우id
, 할 수 있습니다.
$("#theId").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
아니면 어떤 형태로든id
(예: "내 양식") 모든 양식 필드에 대해 이 작업을 수행할 수 있습니다.
$("#myForm input").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
위임을 통해 수행할 수도 있습니다.
$("#myForm").delegate("input", "click", function() {
if (this.value === "TEXT") {
this.value = '';
}
});
이것은 각 개별 입력에 핸들러를 연결하는 것이 아니라 양식에 있는 핸들러를 연결하는 데 사용됩니다.
플레이스홀더를 하려고 한다면, 그 이상의 것이 있을 수 있으며, 이를 수행할 수 있는 좋은 플러그인을 찾고 싶을 수도 있습니다.하지만 기본적인 사항은 다음과 같습니다.
HTML:
<form id='theForm'>
<label>Field 1:
<input type='text' value='provide a value for field 1'>
</label>
<br><label>Field 2:
<input type='text' value='provide a value for field 2'>
</label>
<br><label>Field 3:
<input type='text' value='provide a value for field 3'>
</label>
</form>
jQuery를 사용하는 자바스크립트:
jQuery(function($) {
// Save the initial values of the inputs as placeholder text
$('#theForm input').attr("data-placeholdertext", function() {
return this.value;
});
// Hook up a handler to delete the placeholder text on focus,
// and put it back on blur
$('#theForm')
.delegate('input', 'focus', function() {
if (this.value === $(this).attr("data-placeholdertext")) {
this.value = '';
}
})
.delegate('input', 'blur', function() {
if (this.value.length == 0) {
this.value = $(this).attr("data-placeholdertext");
}
});
});
물론 HTML5의 새 속성을 사용할 수도 있으며 코드가 이를 지원하지 않는 브라우저에서 실행 중인 경우에만 위와 같은 작업을 수행할 수 있습니다. 이 경우 위에서 사용한 논리를 뒤집기를 원합니다.
HTML:
<form id='theForm'>
<label>Field 1:
<input type='text' placeholder='provide a value for field 1'>
</label>
<br><label>Field 2:
<input type='text' placeholder='provide a value for field 2'>
</label>
<br><label>Field 3:
<input type='text' placeholder='provide a value for field 3'>
</label>
</form>
jQuery가 포함된 자바스크립트:
jQuery(function($) {
// Is placeholder supported?
if ('placeholder' in document.createElement('input')) {
// Yes, no need for us to do it
display("This browser supports automatic placeholders");
}
else {
// No, do it manually
display("Manual placeholders");
// Set the initial values of the inputs as placeholder text
$('#theForm input').val(function() {
if (this.value.length == 0) {
return $(this).attr('placeholder');
}
});
// Hook up a handler to delete the placeholder text on focus,
// and put it back on blur
$('#theForm')
.delegate('input', 'focus', function() {
if (this.value === $(this).attr("placeholder")) {
this.value = '';
}
})
.delegate('input', 'blur', function() {
if (this.value.length == 0) {
this.value = $(this).attr("placeholder");
}
});
}
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
(기능-detection 코드를 보려면 diveintohtml5.ep.io 로 이동하십시오.)
이거 드셔보세요.
$('#myFieldID').focus(function(){
$(this).val('');
});
$("input:text").focus(function(){$(this).val("")});
텍스트 상자에 레이블이 포함된 효과를 생성하려고 합니다.그리고 사용자가 텍스트 상자를 클릭하면 사라져서 사용자가 텍스트를 입력할 수 있게 됩니다.당신은 이것에 Jquery를 필요로 하지 않습니다.
<input type="text" value="Input Text" onfocus="this.value=''" onblur="(this.value=='')? this.value='Input Text':this.value;" />
효과가 있었습니다.
**//Click The Button**
$('#yourButton').click(function(){
**//What you want to do with your button**
//YOUR CODE COMES HERE
**//CLEAR THE INPUT**
$('#yourInput').val('');
});
따라서 먼저 jQuery로 버튼을 선택합니다.
$('#button').click(function((){ //Then you get the input element $('#input')
//Then you clear the value by adding:
.val(' '); });
jQuery 사용 중...
$('#submitButtonsId').click(
function(){
$(#myTextInput).val('');
});
순수 자바스크립트 사용 중...
var btn = document.getElementById('submitButton');
btn.onclick = function(){ document.getElementById('myTextInput').value="" };
이를 위한 우아한 방법이 있습니다.
<input type="text" value="Search" name=""
onfocus="if (this.value == 'Search') {this.value = '';}"
onblur="if (this.value == '') {this.value = 'Pesquisa';}"/>
이런 식으로 검색 상자 안에 입력하면 상자 안을 다시 클릭해도 삭제되지 않습니다.
function submitForm() { if (testSubmit()) { document.forms["myForm"].submit(); //first submit document.forms["myForm"].reset(); //and then reset the form values } } </script> <body> <form method="get" name="myForm"> First Name: <input type="text" name="input1"/> <br/> Last Name: <input type="text" name="input2"/> <br/> <input type="button" value="Submit" onclick="submitForm()"/> </form>
자리 표시자와 같은 행동이 필요한 경우.이거 쓰셔도 돼요.
$("selector").data("DefaultText", SetYourDefaultTextHere);
// You can also define the DefaultText as attribute and access that using attr() function
$("selector").focus(function(){
if($(this).val() == $(this).data("DefaultText"))
$(this).val('');
});
이거 먹어봐요.
$("input[name=search-mini]").on("search", function() {
//do something for search
});
저도 같은 문제가 있어서 이걸 사용하는 것을 추천합니다.
$('input:text').focus(
function(){
$(this).val('');
});
$('.mybtn').on('click',
function(){
$('#myinput').attr('value', '');
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="mybtn">CLEAR</button>
<input type="text" id="myinput" name="myinput" value="ааааааааа">
enter code here<form id="form">
<input type="text"><input type="text"><input type="text">
<input type="button" id="new">
</form>
<form id="form1">
<input type="text"><input type="text"><input type="text">
<input type="button" id="new1">
</form>
<script type="text/javascript">
$(document).ready(function(e) {
$("#new").click( function(){
//alert("fegf");
$("#form input").val('');
});
$("#new1").click( function(){
//alert("fegf");
$("#form1 input").val('');
});
});
</script>
언급URL : https://stackoverflow.com/questions/5777674/how-can-i-clear-the-input-text-after-clicking
'it-source' 카테고리의 다른 글
macOS pwsh에서 "지원되는 WSMan 클라이언트 라이브러리를 찾을 수 없습니다." 오류가 발생했습니다. (0) | 2023.09.23 |
---|---|
printf () \t옵션 (0) | 2023.09.23 |
ToMany 관계에 속하는 관련 래벨 모델에서 ID 배열을 가져옵니다. (0) | 2023.09.23 |
워드프레스 사이트 git에서의 협업.데이터베이스를 공유하는 방법? (0) | 2023.09.23 |
리소스 폴더에서 파일 목록 가져오기 - iOS (0) | 2023.09.18 |