user959443
user959443

Reputation: 97

Adding Javascript Text Watermark doesnt work

I am trying to create a textbox watermark using javascript but with the current code I get a error

Webpage error details Message: 'searchInput' is undefined

<script type="text/javascript" language="javascript">

function watermark(inputId,text){ 

  var inputBox = document.getElementById(searchInput); 

      if (inputBox.value.length > 0){  

           if (inputBox.value == text)  

                  inputBox.value = '';
  }   
    else   
       inputBox.value = text;
 }
</script>

<input name="keyword2" id="searchInput" type="text" class="searchbox2"
       value="Enter a State, County, City or Zip" size="77" maxlength="30"
       onfocus="watermark('searchInput','Enter a State, County, City or Zip');"
       onblur="watermark('searchInput','Enter a State, County, City or Zip');"/>

Upvotes: 0

Views: 437

Answers (3)

sdo
sdo

Reputation: 662

You need to put quotes around your search input getElementById Declaration, like so:

document.getElementById('searchInput');

Also, a more direct and simple way of doing this is by putting this in your input:

onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"

Hope this helps :)

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

The variable your function expects is named inputId not searchInput..

So change this line

var inputBox = document.getElementById(searchInput); 

to

var inputBox = document.getElementById(inputId); 

An alternative

And to avoid naming the element completely, just pass this as the first argument as it will reference the element

function watermark(element, text) {
    if (element.value.length > 0) {
        if (element.value == text) {
            element.value = '';
        }
    }
    else element.value = text;
}

and

<input name="keyword2" id="searchInput" type="text" class="searchbox2"
       value="Enter a State, County, City or Zip" size="77" maxlength="30"
       onfocus="watermark(this,'Enter a State, County, City or Zip');"
       onblur="watermark(this,'Enter a State, County, City or Zip');"/>

demo at http://jsfiddle.net/ZtutT/

Upvotes: 1

ChrisR
ChrisR

Reputation: 14447

Add quotes around searchInput.

getElementById accepts a string, you are referencing an undeclared variable.

document.getElementById('searchInput'); 

Upvotes: 0

Related Questions