getElementById doesn't work correctly

getelementbyid, javascript

Solution

Instead of this

<a href='javascript:document.getElementById("mytext2").value = "My default value"; '>click</a><br/> 

Use like this

<a href='javascript:document.getElementById("mytext2").value = "My default value"; return false;'>click</a><br/> 

Excellent explanation from @Jonathan Lonowski

To explain the need for `return false` or similar, `javascript:...` will display the result if it's truthy -- e.g. `href="javascript:"foo"`. `elem()` returns `undefined` by default, which is falsy. But, the assignment operator (`=`) returns the value being assigned. Another option is to prefix the statement with the `void` operator to discard any possible results -- `href="javascript:void document....`". –

Problem

Here is my code - http://jsfiddle.net/EC6jT/ ``` <input type="text" id="mytext"> <a href='javascript:elem();'>click</a><br/> <input type="text" id="mytext2"> <a href='javascript:document.getElementById("mytext2").value = "My default value";'>click</a><br/> <script type="text/javascript"> function elem() { document.getElementById("mytext").value = "My default value"; }; </script> ``` Why is it that the first "click" link works correctly and the second one doesn't? Why is the second "click" link erases everything? Thanks.

Original source