0

So I have this contact form and I want to put text inside each input, when the user clicks on it the text disappears so they can add stuff - when the user clicks on something else it reappears. I have done this with labels and negative margin along with position relative. I plan on adding an onclick function to each input.

My question is - is there a function that is like Offclick()? Or something similiar to mouseOver() and MouseOut()?

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
Howdy_McGee
  • 10,422
  • 29
  • 111
  • 186
  • possible duplicate of [mouse click somewhere else on page (not on a specific div)](http://stackoverflow.com/questions/3440022/mouse-click-somewhere-else-on-page-not-on-a-specific-div) – jAndy Aug 03 '11 at 19:17

2 Answers2

2

Text inputs have onblur and select boxes have onchange events that can be wired into.

<input type="text" id="UserName" name="UserName" value="Placeholder ..." />

<script type="text/javascript">
var el = document.getElementById("UserName");
var original_text = el.value;
el.onblur = function() {
    // `this` is set to the input element by the browser
    if ( ! this.value ) {
        this.value = original_text;
    }
};
</script>

With jQuery, it is even easier:

var el = $("#UserName");
var original_text = el.val();
el.blur(function(){
    // `this` is set to the input element by jQuery.
    if ( ! this.value ) {
        this.value = original_text;
    }
 });
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • So I can do the add text with the onblur() function probably instead of labels and margins huh? – Howdy_McGee Aug 03 '11 at 19:16
  • @Howdy_McGee - absolutely. And if you want to, you can use the HTML5 `placeholder` attribute to get the effect without any JavaScript in supported browsers. http://caniuse.com/#search=placeholder – Sean Vieira Aug 03 '11 at 19:23
  • Well with HTML5 I run the IE8 problem :( - One day i'll be able to use HTML5 effectively xD – Howdy_McGee Aug 03 '11 at 19:43
0

set title attribute same as value for textboxes and then write:

$("input[type=text]").bind("focus",function(){
var $this = $(this);
if($this.attr("title") ==$this.val()){
$this.val('');
}).bind("blur",function(){

var $this = $(this);
if($this.val() ==''){
$this.val($this.attr("title"));
});

or you could use a ready made solution like : http://code.google.com/p/jquery-watermark/

ZeNo
  • 1,648
  • 2
  • 15
  • 28