jQuery alter input value on focus and blur

Discussion in 'Web Design and Development' started by jordanste, Jan 22, 2009.

  1. jordanste macrumors member

    Joined:
    Feb 25, 2006
    #1
    i have a number of input fields throughout my page, each with a description as its value.

    ex:
    HTML:
    <input type="text" value="DESC" />
    i am trying to get jQuery to remove this description from the input field on focus, and then replace it on blur if no other content was entered.

    i am extremely unfamiliar with jQuery and what i came up with doesnt work at all, this is what i have
    Code:
    	$(document).ready(function() {
    		$('input').focus(function() {
    			var value=$(this).val();
    			$(this).val("");
    		});
    		$('input').blur(function() {
    			if($(this).val()=="") {
    				$(this).val(value);
    			}
    		});
    	});
    note: i want this to work for all input fields anywhere on the site, as i dont want to use labels for my forms.

    does anyone have a better way of doing this, or did i mess up with syntax or something?

    thanks.
     
  2. SrWebDeveloper macrumors 68000

    SrWebDeveloper

    Joined:
    Dec 7, 2007
    Location:
    Alexandria, VA, USA
    #2
    You mean onFocus store then remove the value of the input field, then onBlur if the value is blank replace it with the original stored value? "DESC" is really a value in your HTML example, there is no "description" part of an input field - to avoid confusion.

    It seems you need to make the variable you named "value" global. I am not sure it's available in the private function scope the way you have it now, hence the advice. So declare it outside the functions, remove the "var" in line 3, keep the rest the same. This advice is based on only what you posted here.

    If that doesn't do it then add debugging code to echo the value of $this.val() to an alert or window.status for each function to see how it's being set.

    I don't see any obvious syntax error issues, but if you get any let me know what the errors or warnings are in the error console for your browser (i.e. in FF3, go to Tools -> Error Console). If it comes to that, post the entire HTML and JS here as well.

    -jim
     
  3. jordanste thread starter macrumors member

    Joined:
    Feb 25, 2006
    #3
    Thanks Jim, you have always been of great assistance. I did what you suggested with the value variable and now have this...
    Code:
    		$('input, textarea').focus(function() {
    			value=$(this).val();
    			$(this).attr("value","");
    		});
    		$('input, textarea').blur(function() {
    			if($(this).val()=="") {
    				$(this).val(value);
    			}
    		});
    This works wonderfully, but i didn't anticipate the fact that even after a user enters information into a field, upon blur and re-focus, the input is removed. i need a way to test if the value in the field is the original value or a user inputted value.

    i tried this within the focus function
    Code:
    if($(this).val()=="Search"||"Name"||"E-mail Address"||"Comments...") {
    				$(this).attr("value","");
    			}
    ...but that does not work at all.

    Is there a way to grab all input element values on page load, insert them into an array or something and test against that upon each focus?

    also, for reference, this is the comment form i am working with...
    HTML:
    <div id="comments">
    	<h3>Comments</h3>";
    	<form action="#" method="post">
    		<input type="text" name="name" id="name" size="40" value="Name" /><br />
    		<input type="text" name="email" id="email" size="40" value="E-mail Address" /><br />
    		<input type="text" name="website" id="website" size="40" value="http://" /><br />
    		<textarea name="comment" id="comment" rows="6" cols="38">Comment...</textarea><br />
    		<input type="submit" value="Post" />
    	</form>
    </div>
     
  4. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #4
    This,
    PHP:
    if($(this).val()=="Search"||"Name"||"E-mail Address"||"Comments...") {
                    $(
    this).attr("value","");
                }
    would need to be in this format,
    PHP:
    if($(this).val() != "Search" && $(this).val() != "Name"
        
    && $(this).val() != "E-mail Address" && $(this).val() != "Comments...") {
      $(
    this).attr("value","");
    }
    There's other ways as well (without jQuery). If I get a chance I'll put up something later.
     
  5. SrWebDeveloper macrumors 68000

    SrWebDeveloper

    Joined:
    Dec 7, 2007
    Location:
    Alexandria, VA, USA
    #5
    @jordanste

    Angelwatt apparently posted a nice solution for you which would work fine as long as the form isn't too long, i.e. for the simple form you're doing no need to worry with storing stuff in an array, etc. -- the code posted here gets it done.

    But your concept about grabbing form field values and retaining them in memory would be the correct approach if you had long forms or wished to create a function you can call for almost any form as part of a kick-butt validation routine.

    In that scenario, it's the same situation as I advised earlier, just declare an array globally, loop through all document.form elements with type input, store the value using the form field name as the keyname of the array.

    $myarray['email']="...the value of the email field...";

    And instead of hardcoding data as was done in the last few replies here, instead loop through the array and compare the values that way.

    I don't have time to code this out for you and besides, your original question was asked/resolved - but you get the idea. Angelwatt is going to post some alternative stuff anyway so one way or another you'll get it done.
     
  6. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #6
    That didn't take long. Below is a partial jQuery solution. I don't really use it so not want to mess with the syntax too much. I believe I used the right syntax to make this code run once the DOM is ready. If you, or someone else here who is more jQuery savvy, want you can rework some of the code to be more jQuery efficient, but the code has been tested otherwise and works nicely.
    PHP:
    $(document).ready(function(){
      var 
    input document.getElementsByTagName('input');
      for (var 
    a=input.length-1>= 0a--) {
        if (
    input[a].type != 'txt') { continue; } // skips non-text inputs
        
    input[a].mask input[a].value;
        
    input[a].onfocus = function() {
          if (
    this.value == this.mask) { this.value ''; }
        };
        
    input[a].onblur = function() {
          if (
    this.value == '') { this.value this.mask; }
        };
      }
    });
     
  7. Benxamin macrumors newbie

    Joined:
    Oct 18, 2010
    #7
    To ensure cross-browser compatibility and consistent usability, this problem was solved a long time ago, jQuery or not.

    You need a somewhatbadass trim() function to determine if they've entered a bunch of whitespace. Using javascript's native regular expression is a quick way to do this.

    Code:
    function trim(str) 
    {
        str = str.replace(/^\s+/, '');
        
        for (var i = str.length - 1; i > 0; i--) 
        {
            if (/\S/.test(str.charAt(i))) 
            {
                str = str.substring(0, i + 1);
                break;
            }
        }
        
        return str;
    };
    
    Once you have your trim(), you can now use it to check the values of the form field on focus and blur.

    Code:
    function default_value(someElement)
    {
        if (trim(someElement.value) == someElement.defaultValue)
        {
            someElement.value = '';
        }
    };
    
    function new_value(someElement)
    {
    	if (trim(someElement.value) == '')
    	{
    		someElement.value = someElement.defaultValue;
    	}
    	else
    	{
    	   someElement.value = trim(someElement.value);
    	}
    };
    
    Then, to use these functions, just add them to your input elements.

    HTML:
    <input type="text" value="Search this site" id="global_search" onfocus="default_value(this);" onblur="new_value(this);" />
    Now with prototype or jQuery it's more convenient to grab the input(s) and invoke default_value() and new_value() on focus and blur, respectively.
    It's pretty easy, so I'll leave the details to how you want to do it. But here's the parts. ;)
     
  8. logotoxic macrumors newbie

    Joined:
    Oct 30, 2010
    #8
    Try this

    HTML:
    $(document).ready(function(){
    
    $('input:text').focus(function(){
    	var newValue = $(this).val();
    	if($(this).val() == 'your desc'){
    		$(this).attr('value','');
    		} else {
    			$(this).val(newValue);
    			}
    });
    
    $('input:text').blur(function(){
    	var newValue = $(this).val();
    	if($(this).val() == ''){
    		$(this).attr('value','your desc');
    		} else {
    			$(this).val(newValue);
    			}
    	});
    });
    ... and in HTML
    HTML:
    <input name="name" id="id" value="your desc" type="text">
    HTH

    Peter
     

Share This Page