April 30, 201016 yr Hey guys, I'm either having a dumb moment here, or I just can't find the answer, but I've written a script using jQuery that takes the elements of my form, checks to see if the default value is currently displayed on focus, if so the field is set to blank. My problem is on blur. I want to loop through my default value array, find the name that corresponds to the input name, and add the default value to the input field. Hopefully this makes sense to you guys, I've attached the code below: var defaults = { 'name' : 'Enter your name..', 'email' : 'Your e-mail address so I can reply..', 'website' : 'Your existing website (optional)', 'subject' : 'The subject of your message..', 'message' : 'Your message..' }; $("input, select, textarea").focus(function() { var val = $(this); $.each(defaults, function(key, value) { if (val.val() == value || val.val() == "") { val.val(""); return false; } }); }); $("input, select, textarea").blur(function() { var val = $(this); $.each(defaults, function(key, value) { if (val.val() == "") { //what do i write?! } }); }); Any help is appreciated.
April 30, 201016 yr Umm...to simplify the whole thing; $(document).ready(function(){ $("input, select, textarea").focus(function() { if (this.value == this.defaultValue) { this.value = ""; } }); $("input, select, textarea").blur(function() { if (this.value == "") { this.value = this.defaultValue; } }); }); Replace all the code you posted above with that and you should be set to go. Forgive me if it's buggy - it's late
April 30, 201016 yr Author where does defaultValue come from? Can I just write.. <input type="text" name="name" value="Enter your name.." defaultValue="Enter your name.." /> Thanks
April 30, 201016 yr where does defaultValue come from? Can I just write.. <input type="text" name="name" value="Enter your name.." defaultValue="Enter your name.." /> Thanks defaultValue is the original value of the value attribute. You don't need to add it, just put something in the value attribute
Create an account or sign in to comment