Stumf
Stumf

Reputation: 941

Problem Clearing TextBox in JavaScript

I am new to this, but I am trying to clear whatever content is in a text box. The code I have in the body section is as follows:

<body>

<FORM NAME = "frmOne" method=POST>

 Name: <INPUT TYPE=text NAME=name onFocus="this.form.name.value=''" /><br />

 <input type="button" value="Click To Clear" onClick="clearForm(this.form)">


 </FORM>

<SCRIPT LANGUAGE="JAVASCRIPT">

function clearForm(form){

form.name.value = "";

</SCRIPT>

</body>

Problem is, clicking the button does nothing and anything in the Name box remains there! Can anyone suggest why? I am probably making a very basic mistake.

Thanks,

Stuart

Upvotes: 0

Views: 770

Answers (2)

jli
jli

Reputation: 6623

Instead of using name, its good practise to use ids.

So for your input, use:

<INPUT TYPE=text NAME=name ID="myFormTextbox" onFocus="this.value=''" /><br />

And for your js:

function clearForm(form) {
    document.getElementById("myFormTextbox").value = "";
}

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

It's because you have a syntax error, you are missing a }. It should be:

function clearForm(form){
    form.name.value = "";
} // <- you have to close the function

Then it works.

Tools like Chrome developer tools or Firebug for Firefox help you to detect such errors. For example, your code results in the following error:

Uncaught SyntaxError: Unexpected end of input

Upvotes: 4

Related Questions