1

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>
1
  • 1
    Well, when is myFunction called? Commented Apr 22, 2019 at 16:20

3 Answers 3

2

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..)

Sign up to request clarification or add additional context in comments.

Comments

1

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">

Comments

0

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.