IT TIP

클릭 후 입력 텍스트를 지우려면 어떻게합니까

itqueen 2020. 11. 29. 12:46
반응형

클릭 후 입력 텍스트를 지우려면 어떻게합니까


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")이 있는 양식에 있고 모든 양식 필드에 대해이 작업을 수행하려는 경우 :

$("#myForm input").click(function() {
    if (this.value === "TEXT") {
        this.value = '';
    }
});

위임을 사용하여 수행 할 수도 있습니다.

$("#myForm").delegate("input", "click", function() {
    if (this.value === "TEXT") {
        this.value = '';
    }
});

이는 delegate양식의 핸들러를 연결하는 데 사용 하지만 각 개별 입력에 핸들러를 연결하는 대신 양식의 입력에 적용합니다.


자리 표시자를 사용하려는 경우 그보다 더 많은 것이 있으며이를 수행 할 수있는 좋은 플러그인을 찾는 것이 좋습니다. 하지만 기본 사항은 다음과 같습니다.

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를 사용하는 JavaScript :

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 의 새 placeholder속성사용할 수도 있으며 코드가이를 지원하지 않는 브라우저에서 실행중인 경우에만 위의 작업을 수행 할 수 있습니다.이 경우 위에서 사용한 논리를 반전시키려는 경우 :

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를 사용한 JavaScript :

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);
  }

});

라이브 카피

( placholder기능 감지 코드 는 diveintohtml5.ep.io에 대한 찬사입니다 .)


$("input:text").focus(function(){$(this).val("")});

당신은 이것을 시도 할 수 있습니다

$('#myFieldID').focus(function(){
  $(this).val('');
});

I am supposing you are trying to create a effect, where the textbox contains a label. And when the user click in the textbox, it disappears and lets the user input the text. You do not require Jquery for this.

<input type="text" value="Input Text" onfocus="this.value=''" onblur="(this.value=='')? this.value='Input Text':this.value;" />

Demo


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>


This worked for me:

    **//Click The Button**    
    $('#yourButton').click(function(){

         **//What you want to do with your button**
         //YOUR CODE COMES HERE

         **//CLEAR THE INPUT**
         $('#yourInput').val('');

});

So first, you select your button with jQuery:

$('#button').click(function((){ //Then you get the input element $('#input')
    //Then you clear the value by adding:
    .val(' '); });

Using jQuery ...

$('#submitButtonsId').click(
    function(){
        $(#myTextInput).val('');
    });

Using pure Javascript ...

var btn = document.getElementById('submitButton');
btn.onclick = function(){ document.getElementById('myTextInput').value="" };

If you need placeholder like behavior. you can use this.

$("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('');
});

try this

$("input[name=search-mini]").on("search", function() {
 //do something for search
});

There is an elegant way to do this:

<input type="text" value="Search" name="" 
       onfocus="if (this.value == 'Search') {this.value = '';}" 
       onblur="if (this.value == '') {this.value = 'Pesquisa';}"/>

In this way, if you type anything inside the search box, it won't be deleted when click inside the box again.


I would recommend to use this since I have the same issue which got fixed.

$('input:text').focus(
    function(){
        $(this).val('');
    });

    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

반응형