[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to undo or default back in jquery?

Posted on 2011-04-20
24
Medium Priority
?
541 Views
Last Modified: 2012-05-11
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??
0
Comment
Question by:FairyBusiness
  • 7
  • 6
  • 6
  • +4
23 Comments
 
LVL 2

Expert Comment

by:jainnaveen
ID: 35438349
       $(function() {
            $("#txtOne").focusout(function(e) {
                if ($("#txtOne").val() == "")
                    $("#txtOne").val("default value");
                return false;
            })
        });
0
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 35438365
<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
 

Author Comment

by:FairyBusiness
ID: 35438390
What does returning it false do??
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 35438402
nothing
it will display the whatever value is enterd in that
0
 

Author Comment

by:FairyBusiness
ID: 35438404
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
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 35438417
$('.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
 

Author Comment

by:FairyBusiness
ID: 35438427
Well, I am only using jquery for this and so far nothing as worked. . .
0
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 35438433
try like this
$('.text').onBlur(function(e) {
if ( $(this).val().length == 0 )
      $(this).val('Defualt');
});
0
 

Author Comment

by:FairyBusiness
ID: 35438446
Nope, that didnt work either. . .

They disappear but do not come back

http://auroriella.com/story.html
0
 
LVL 2

Expert Comment

by:jainnaveen
ID: 35438447
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
 

Author Comment

by:FairyBusiness
ID: 35438456
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
 
LVL 2

Expert Comment

by:jainnaveen
ID: 35438465
oh, it's just preventing default !
0
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 35438469
try this

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

$('.text').onBlur(function(e) {
      $(this).val = ($(this).val()|| "Default"));
});
0
 
LVL 2

Expert Comment

by:jainnaveen
ID: 35438470
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
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 35438474
$('.text').onBlur(function(e) {
      $(this).val = ($(this).val()|| "Default"));
return true;
});
0
 

Author Comment

by:FairyBusiness
ID: 35438490
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
 
LVL 2

Expert Comment

by:jainnaveen
ID: 35438496
take it easy ! anyway I am off this easter holidays. Happy Easter
0
 
LVL 2

Expert Comment

by:jainnaveen
ID: 35438549
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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 35438712
PS:

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


if ($(this).val() == "") {
  $(this).val($(this)[0].defaultValue);
}
0
 
LVL 5

Accepted Solution

by:
dnzone88 earned 2000 total points
ID: 35438824
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
 
LVL 9

Expert Comment

by:Roman Gherman
ID: 35438851
take a look at this jquery watermark plugin:

http://mal.co.nz/code/jquery-placeholder/
0
 
LVL 29

Expert Comment

by:Badotz
ID: 35440826
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
 

Author Closing Comment

by:FairyBusiness
ID: 35442689
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question