Skip to content

Instantly share code, notes, and snippets.

@absent1706
Last active February 1, 2017 14:37
Show Gist options
  • Select an option

  • Save absent1706/e485a2e8f4f7412f5b2e234e785e3110 to your computer and use it in GitHub Desktop.

Select an option

Save absent1706/e485a2e8f4f7412f5b2e234e785e3110 to your computer and use it in GitHub Desktop.
JS form hacks: reset button, clean empty fields
/*
* Handler for reset button that cleans all form fields and submits form
* See http://www.javascript-coder.com/javascript-form/javascript-reset-form.phtml
*/
$('.js-reset-closest-form').click(function() {
var form = $(this).closest('form')[0];
/* it's important to take form.elements, not just $(form).find(input)
* because inputs can be OUTSIDE <form> tag, i.g.:
* <form id="search-form"> ... </form>
* ...
* <input form="search-form" ..>
*/
$(form.elements).each(function(_, field){
if (field.name) {
var field_type = field.type.toLowerCase();
switch (field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
field.value = "";
break;
case "radio":
case "checkbox":
if (field.checked) {
field.checked = false;
}
break;
case "select-one":
case "select-multi":
field.selectedIndex = -1;
break;
default:
break;
}
}
});
$(form).submit();
});
/*
* Add below class to forms on which you want to skip sending empty fields
* (to prevent ugly URLs like /page?search=&search2=)
*/
$('.js-dont-send-empty-fields').submit(function(){
/* it's important to take form.elements, not just $(form).find(input)
* because inputs can be OUTSIDE <form> tag, i.g.:
* <form id="search-form"> ... </form>
* ...
* <input form="search-form" ..>
*/
$(this.elements).each(function(_, field){
var field_type = field.type.toLowerCase();
if (field.name && (field.value == '') && (['text','password', 'textarea', 'hidden'].indexOf(field_type) !== -1)) {
$(field).prop('name', '');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment