This is my first time working with jQuery and I’m having some difficulty understanding how to implement it on my website, even though its a relatively easy task I am trying to accomplish.
My goal is to modify an existing textarea on my website so that it has a default message displayed that disappears when the client clicks on the textarea to enter his information. Originally I just wanted to use the html placeholder attribute, but for some reason it does not work.. (I am using IE 8). So now I am trying to use this jQuery code which was suggested to me.
Here is the code:
<textarea style="background: #F6E3CE; overflow:auto;" rows="3" cols="70" name="sComments" id="sComments"
<script type="text/javascript"><?php
$("input#text").focus(function(){
if( $(this).val() == "default message" )
{
$(this).val("");
}
}).blur(function(){
if( $(this).val() == "" )
{
$(this).val("default message");
}
}); ?>
</script>
onchange="commentsChanged(this,<?php echo $pKey;?>);"><?php echo str_replace('\r\n', "\n", rtrim($variable1[0][aComments]));?></textarea>
If I understand correctly, I referenced the jQuery file at the beginning of my code as such:
<script language="JavaScript" src="../js/jquery-1.6.4.js"></script>
On this latest attempt, this part of the website would not even open. After doing some research I am still unsure what I am doing wrong.
Thank you.
EDIT: Both answers below are excellent and work great. Tenhouse’s is more “proper” because it seperates logic and formatting, but Chandrakant’s use of inline JavaScript works equally as well and is actually what I used on my website.
First off you are mixing up
PHPcode withJavaScriptcode which will not work, since they are in no direct relation.Secondly you have to put your
focus / blur -listenersin thedocument readyfunction (this means it will load when the document is loaded).Thirdly I highly recommend to read some about the basics of jQuery – you could start with this:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Edit: Since you really seem to be very confused about everything, here a full example:
In the example above you can also see that I use a newer jQuery-Version – directly from their servers.
Viewing the other answer of Chandrakant:
I don’t agree putting the JavaScript part directly into the element. It’s not a good practice, since you should always try to split logic & formatting.