Using jQuery to supply and clear default input values ================================================================================ This is a repost of a solution I provided over at the smashing magazine forums. I’m posting it here as it’s a pretty useful solution in itself. The original question is as follows: I’m building a new website and on this one page I need to use a huge form, instead of using labels I want to enter the “label” text in the value attribute and then use JS to clear the field on mouseclick. The problem is that every field needs to be filled out. I don’t want users hitting the submit button with some of the standard values still in place (easy to miss certain stuff) because this will mess things up. I can ofcourse check for empty fields but to do this I need to somehow check if all the fields have been changed on form submit. So I whipped up a quick implementation of how I would do it using jQuery. HTML:
A bit of CSS styling: #someForm { display: block; text-align: left; padding: 20px; margin: 0 auto; width: 400px; } .someLabel { clear: both; display: block; } .someInput { clear: both; display: block; margin-bottom: 10px; } button { clear: both; } jQuery: $(function(){ var inputs = $(".someInput"); var labels = $(".someLabel"); $.each( inputs, function(){ var index = inputs.index(this); if($(this).val()==""){ $(this).attr("value",labels.eq(index).text()); } $(this).focus(function(){ if($(this).val()==labels.eq(index).text()){ $(this).attr("value",""); } }); $(this).blur(function(){ if($(this).val()==""){ $(this).attr("value",labels.eq(index).text()); } }); }); }); If you don’t want to assign classes to each of the form inputs and labels, you could select them based on something like $("#formId input"), and $("#formId label") instead. Additionally, if you wanted to hide the label elements too, you could add the following line after the first variable declarations: labels.each(function(){$(this).hide();}); ================================================================================ Published January 10, 2010 Generated from the original post: https://blog.omgmog.net/post/using-jquery-to-supply-and-clear-default-input-values/ Max Glenister is an interface designer and senior full-stack developer from Oxfordshire. He writes mostly about front-end development and technology. - Mastodon: https://indieweb.social/@omgmog - Github: https://github.com/omgmog - Reddit: https://reddit.com/u/omgmog - Discord: https://discordapp.com/users/omgmog#6206