I am new with html and javascript. I have been trying to modify the value of an input element with javascript. The purpose is to set the field blank when user clicks it. the code is as below:
<html>
<head>
<script>
function fn(){
if(document.input1.value=="name")
document.input1.value="";
}</script></head>
<body>
<input name="input1" type="text" value="name" onClick="fn()"/>
</body></html>
However, this code is not working. I am using a chrome browser. When I surround the input tag with a form tag and in script I use document.form.input1.value the code works. where is the problem? I am not concerned about how to blank the field on user click, rather how to access the value from a function. Thanks in advance.
You may also want to try the
onFocusandonBlurevents:EXAMPLE
EDIT:
If you prefer to get the element by its name, you can use
document.getElementsByName, however, this returns a list of all matching elements and you would then treat it as an array of matched elements. In the case above, you would switchdocument.getElementById("input1")withdocument.getElementsByName("input1")[0]