How to undo or default back in jquery?

Hi, I have a function that when click removes the default values of the text input fields:

$('.text').click(function(e) {
    e.preventDefault();
      $(this).val('');
});

But I want the default values to appear back if the user does not enter anything (click on something else).  Anyone know how to accomplish this??
FairyBusinessAsked:
Who is Participating?
 
dnzone88Commented:
Here are some examples of how you can save the value and retrieve it using jQuery .data() API.

<meta http-equiv="Content-Type" content="text/html; charset=encoding">
<title>Insert title here</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$('.lastInputValue').click(function() {
		// store the default value then set the input box empty
		$(this).data('input_default', $(this).val()).val('');
	}).blur(function(){
		if($(this).val()==""){
			// if input box is empty restore the value
			$(this).val($(this).data('input_default'));
		}
		// clear the saved value
		$(this).removeData('input_default');
	});
	
	$('.defaultValue').data('input_default','Enter Your Name').click(function() {
		// set the input box empty
		$(this).val('');
	}).blur(function(){
		if($(this).val()==""){
			// if input box is empty restore the default value
			$(this).val($(this).data('input_default'));
		}
	});
});
</script>
</head>
<body>
<label>Last Input Value</label><input type="text" class="lastInputValue" value="" />
<br />
<label>Default Value</label><input type="text" class="defaultValue" value="Enter Your Name" />
</body>
</html>

Open in new window


Hope it help.
0
 
jainnaveenCommented:
       $(function() {
            $("#txtOne").focusout(function(e) {
                if ($("#txtOne").val() == "")
                    $("#txtOne").val("default value");
                return false;
            })
        });
0
 
Pratima PharandeCommented:
<INPUT type="text" ID="Text1" NAME="Text1" onclick="document.getElementById('Text1').value=''" value="Default"

 onBlur ="if (document.getElementById('Text1').value=='') document.getElementById('Text1').value ='Default'" >

In your case

$('.text').onBlur(function(e) {
    e.preventDefault();
if ($(this).val.value=='')
      $(this).val('Defualt');
});
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
FairyBusinessAuthor Commented:
What does returning it false do??
0
 
Pratima PharandeCommented:
nothing
it will display the whatever value is enterd in that
0
 
FairyBusinessAuthor Commented:
Both of your guys function prevents my other function from working:

$('#submit').click(function(e) {
    e.preventDefault();
    var name = $('#name').val();
    $("#name2").append(name);
});

Now when I click on a text field the value does not disappear.  Is there a way to make the value disappear when you click on it, but if you leave it blank and click away the default value comes back??
0
 
Pratima PharandeCommented:
$('.text').onBlur(function(e) {
if ($(this).val.value=='')
      $(this).val('Defualt');
});

if you try this is functions as you said

<INPUT type="text" ID="Text1" NAME="Text1" onclick="document.getElementById('Text1').value=''" value="Default"

 onBlur ="if (document.getElementById('Text1').value=='') document.getElementById('Text1').value ='Default'" >
0
 
FairyBusinessAuthor Commented:
Well, I am only using jquery for this and so far nothing as worked. . .
0
 
Pratima PharandeCommented:
try like this
$('.text').onBlur(function(e) {
if ( $(this).val().length == 0 )
      $(this).val('Defualt');
});
0
 
FairyBusinessAuthor Commented:
Nope, that didnt work either. . .

They disappear but do not come back

http://auroriella.com/story.html
0
 
jainnaveenCommented:
Hi Fairy,

follow the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <script language="JavaScript" type="text/javascript" src="jquery-1.4.1.js"></script>
    <script language="JavaScript" type="text/javascript">
        $(function() {
            $("#txtOne").click(function(e) {
                if ($(this).val() == "default value")
                    $(this).val("");
                return false;
            });
            $("#txtOne").focusout(function(e) {
                if ($(this).val() == "")
                    $(this).val("default value");
                return false;
            });            
        });
    </script>
</head>
<body>
    <div style="width: 50%">
        <input type="text" id="txtOne" value="default value" />
    </div>
</body>
</html>
0
 
FairyBusinessAuthor Commented:
this did not work for me:

$(function() {
            $(".text").click(function(e) {
                if ($(this).val() == "default value")
                    $(this).val("");
                return false;
            });
            $(".text").focusout(function(e) {
                if ($(this).val() == "")
                    $(this).val("default value");
                return false;
            });            

I still wish you would tell me why you put return false at the end.  I never know when to put return false, return true, or nothing. . .
0
 
jainnaveenCommented:
oh, it's just preventing default !
0
 
Pratima PharandeCommented:
try this

refer for more info
http://coldfusioncode.adampresley.com/jquery-examples/defaultIfNull.cfm

$('.text').onBlur(function(e) {
      $(this).val = ($(this).val()|| "Default"));
});
0
 
jainnaveenCommented:
have you created html page with what i have sent in my previous comment, if not try doing that and you will understand the logic.
0
 
Pratima PharandeCommented:
$('.text').onBlur(function(e) {
      $(this).val = ($(this).val()|| "Default"));
return true;
});
0
 
FairyBusinessAuthor Commented:
Ok, pratima I tried that last one but it didnt work.  I will try your script tomorrow jainnaveen.  But I'm about to pass out, so tired.  Never thought this would be so confusing. . .
0
 
jainnaveenCommented:
take it easy ! anyway I am off this easter holidays. Happy Easter
0
 
jainnaveenCommented:
Revised version, Have used this in of my works...
pls change the jquery src path that of your


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Text Box - default text</title>
    <script language="JavaScript" type="text/javascript" src="jquery-1.4.1.js"></script>
     <style type="text/css">
         .text {}
     </style>
    <script language="JavaScript" type="text/javascript">
        $(function() {
            $(".text").click(function(e) {
                if ($(this).val() == "default value") {
                    $(this).val("");
                    $(this).css({ color: 'Black' })
                    return false;
                }
                return true;
            });
            $(".text").focusout(function(e) {
                if ($(this).val() == "") {
                    $(this).val("default value");
                    $(this).css({ color: 'Gray' })
                    return false;
                }
                return true;
            });
        });
    </script>
</head>
<body>
    <div style="width: 50%; text-align:center">
        <input type="text" class="text" id="txtOne" style="color:Gray " value="default value" />
    </div>
</body>
</html>
0
 
Michel PlungjanIT ExpertCommented:
PS:

http://www.miuaiga.com/index.cfm/2009/8/31/jQuery-form-input-defaultValue


if ($(this).val() == "") {
  $(this).val($(this)[0].defaultValue);
}
0
 
Roman GhermanSenior Software EngineerCommented:
take a look at this jquery watermark plugin:

http://mal.co.nz/code/jquery-placeholder/
0
 
BadotzCommented:
You might consider something like the following:

Make a list of your input elements and what their default values should be.

Why? I have had trouble with default values "disappearing"; the property just seems unreliable.

Then attach an event handler to the window onclick event, and spin through the list, stuffing default values as needed.

It isn't JQuery, but you can adapt it, if you wish.
<script type="text/javascript">

// Use an anonymous function (do not pollute the global namespace)

(function() {
    var list = ["input_1", "ABC", "input_2", "DEF", "input_3", "GHI"];
    var x;
    
    function window_check() {
        for (var i = 0; i < list.length; i += 2) {
            x = document.getElementById(list[i]); // Reference the input
            if (x.value == "") { x.value = list[i + 1]; } // Reset the default value
        }
        return false;
    }
    
    window.onclick = window_check;

})(); // Invoke the function

<script>

Open in new window

0
 
FairyBusinessAuthor Commented:
This worked on the first try and its in jquery, which is what I was needing. Thank you to everyone who contributed, I learned from other posts as well.  Please don't be shy about posting on my questions in the future!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.