Ishikawa
Ishikawa

Reputation: 177

Javascript for mobile HTML form

I am having some problems with Javascript :( This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.

Here is the Script (in head tag):

<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>

Here is the HTML code:

<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>   

I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?

Upvotes: 1

Views: 221

Answers (3)

Peter Olson
Peter Olson

Reputation: 142921

There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code

 resetDefault();
 {if (this.value.length==0); 
 this.value="default";}

so that it has valid syntax, like this:

function resetDefault(){
 if(this.value.length == 0){
  this.value = "default";
 }
} 

The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change. Change the onblur javascript so that it passes in a parameter to the function:

onblur="resetDefault(this);" 

and change the function so it accepts a parameter:

function resetDefault(that){
    if (that.value.length == 0){
        that.value="default";
    }
}

The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:

that.value = that.getAttribute("default");

Try it out on JSFiddle

Upvotes: 2

Joshua
Joshua

Reputation: 3603

You need to define the resetDefault() function like so:

function resetDefault() {
    // Function stuff here 
}

Upvotes: 0

MaxVT
MaxVT

Reputation: 13234

The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.

<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>

Upvotes: 0

Related Questions