Sometimes Web forms are long. And the longer the form, the more frequently we are plagued by details like field name duplication and making sure the field values show up in the database record or an e-mail.
So for a recent project I whipped together the following JavaScript snippet (for jQuery, of course). The snippet does the following on page load
- All text fields and text areas assume a value equal to their field names
- All select boxes take the value of their first non-empty options
- All radio buttons get the last option checked
- All check boxes are checked
Additionally, radio buttons, select fields, and check boxes each have appended a span tag bearing their field name.
;(function($) { $(function() { // text field values = text field name $.each($("input[type='text']").add("textarea"), function(i, input) { var field = $(input); field.val(field.attr('name')); }); // select field value = first option with non-empty value $.each($('select'), function(i, select) { var field = $(select); $.each(select.options, function(i, option) { if (!select.selectedIndex && option.value != '') select.selectedIndex = 1; }); field.after("<span>"+field.attr('name')+"</span>"); }); // checkboxes = checked $.each($("input[type='checkbox']"), function(i, checkbox) { var field = $(checkbox); checkbox.checked = true; field.after("<span>"+field.attr('name')+"</span>"); }); // radio buttons = last checked $.each($("input[type='radio']"), function(i, radio) { var field = $(radio); radio.checked = true; field.after("<span>"+field.attr('name')+"</span>"); }); }); })(jQuery);copy code
If you use this snippet in your project, there’s no need to credit me with it, but do leave a comment on the blog to let me know what you think.