0
<script>
function clear() {
    document.getElementById('box').value = " ";
    };
</script>

<input type="text" id="box" onFocus="clear()" value="Type name here">

Hi, so i'm fairly new to javascript and I'm trying to clear a text field onFocus. I have searched the site and found other ways to do this, but i was curious as to why this code wouldn't work. Would appreciate any help, thanks :)

1 Answers1

2

Modern day browsers have it built it in. It is the placeholder attribute. No JavaScript is needed.

<input type="text" id="box" placeholder="Type name here">

Reason your code did not run was a name collision with document.clear which is deprecated, if you change the name it works fine.

function xclear() { 
    document.getElementById('box').value = " ";
};
<input type="text" id="box" onFocus="xclear()" value="Type name here">
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thanks yes that is a solution to the problem, but i was really trying to understand why the code wouldn't work. the input has a 'value', and the javascript should change that value but it doesn't.. – Andy Smith Jun 02 '16 at 13:07