简体   繁体   中英

How to clear an input with javascript?

I have 3 inputs:

<label for="text1">Text 1</label>
<input type="text" class="text1" value="To clear"><br>

<label for="text2">Text 2</label>
<input type="text" class="text2" value="to select"><br>

<label for="text3">Text 3</label>
<input type="text" class="text3" value="Click in this field">

I would like that when you click in the text3, it erases the text1. I did a function but it does not work:

<script>
    function myFunction(text3) {
        document.text1.value = "";
    }   
</script>

The correct way of doing this is to assign an event listener to the element, within that you can call your function

 function myFunction() { document.querySelector('input.text1').value = ""; } document.querySelector('input.text3').addEventListener('focus', myFunction); 
 <label for="text1">Text 1</label> <input type="text" class="text1" value="To clear"><br> <label for="text2">Text 2</label> <input type="text" class="text2" value="to select"><br> <label for="text3">Text 3</label> <input type="text" class="text3" value="Click in this field"> 

Make sure to select your elements with DOM methods like querySelector , getElement(s)By... and so on. Never rely on accessing an element by it's global id as this may break depending on used browser. (Though document.text1.value = ""; will never work..)

 var text1 = document.querySelector('.text1'); var text3 = document.querySelector('.text3'); text3.addEventListener('focus', myFunction); function myFunction() { text1.value = ''; } 
 <label for="text1">Text 1</label> <input type="text" class="text1" value="To clear"><br> <label for="text2">Text 2</label> <input type="text" class="text2" value="to select"><br> <label for="text3">Text 3</label> <input type="text" class="text3" value="Click in this field"> 

You can do it very easily using JQuery .

  $('.text3').on('focus', function() { $('.text1').val(''); }) 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <label for="text1">Text 1</label> <input type="text" class="text1" value="To clear"><br> <label for="text2">Text 2</label> <input type="text" class="text2" value="to select"><br> <label for="text3">Text 3</label> <input type="text" class="text3" value="Click in this field"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM