0

I've got input with text type. I want to clear it when I click on it. However my approach does not work

<span class="input"><input type="text" id="input1" onclick="clear()"></span>

Where clear() function is

function clear() {
    alert(event.target.id);
    event.target.value = "";
}

What is the correct way?

lapots
  • 12,553
  • 32
  • 121
  • 242

2 Answers2

2

function name clear does not seem to be working. Change the function name (say, clearMe) and try (Fiddle):

<script>
    function clearMe(x) {
    x.value = "";
}
</script>
<span class="input">
   <input type="text" id="input1" onclick="clearMe(this);" value="abcd" />
</span>

For a single line:

<input type="text" id="input1" onclick="this.value='';" value="abcd" />
Community
  • 1
  • 1
Kaf
  • 33,101
  • 7
  • 58
  • 78
1

The problem is that there is a function document.clear() which is actually called instead of yours!

In this case, you will also see a warning in Google Chrome because the function is deprecated:

document.clear() is deprecated. This method doesn't do anything.
— Google Chrome v30

Choose another name:

function clearA(obj) {
  obj.value = "";
}

<input type="text" id="input1" onclick="clearA(this);" />

Or use real event listeners (which should be the preferred way!):

document.getElementById("input1").addEventListener("click", function () {
  this.value = "";
};
ComFreek
  • 29,044
  • 18
  • 104
  • 156