www.webdeveloper.com
Results 1 to 5 of 5

Thread: jQuery: Need Help w/ Show or Hide on Form Field Click

  1. #1
    Join Date
    Jan 2003
    Posts
    218

    Question jQuery: Need Help w/ Show or Hide on Form Field Click

    I've got a jQuery script I use for hiding/showing default values in small forms:

    Code:
    $("#contactForm .textField").focus(function() {
    	if (!default_values[this.id]) {
    		default_values[this.id] = this.value;
    	}
    	if (this.value == default_values[this.id]) {
    		this.value = '';
    	}
    	$(this).blur(function() {
    		if (this.value == '') {
    			this.value = default_values[this.id];
    		}
    	});
    });
    The issue is that I need to use this script on multiple fields (with the same CSS class) within the same form. What syntax changes need to be made? Right now -- this script will work for the first field you click in -- but won't work for the other fields in the same form.

    Thank you for your help.

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    Your script should work if the IDs of all your text fields are unique.

    However, I do see something not-so-optimal in your script. Every time a text field is focused you add a brand new event listener to that field on the "blur" event. You should add the blur event listener at the same time you add the focus event listener (i.e. only one time).

  3. #3
    Join Date
    Jan 2003
    Posts
    218
    I'll assign IDs to the fields. I was trying to avoid doing this.

    How would the focus/blur correction look?

  4. #4
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    Code:
    $("#contactForm .textField").focus(function() {
    	if (!default_values[this.id]) {
    		default_values[this.id] = this.value;
    	}
    	if (this.value == default_values[this.id]) {
    		this.value = '';
    	}
    }).blur(function() {
    	if (this.value == '') {
    		this.value = default_values[this.id];
    	}
    });

  5. #5
    Join Date
    Jan 2003
    Posts
    218
    Okay. That makes sense. Thank you for your time and help.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles