(function (window) { 'use strict'; function isEmptyValue(value) { return value === null || value === undefined || value === ''; } /** * Build a GET URL from a filter form, omitting empty / unselected fields. * * @param {HTMLFormElement|jQuery} formEl * @param {object} [opts] * @returns {string} */ window.pmsBuildCleanGetQuery = function (formEl, opts) { opts = opts || {}; var form = formEl && formEl.jquery ? formEl[0] : formEl; if (!form) { return window.location.pathname; } var action = form.getAttribute('action') || window.location.pathname; var pairs = []; var seen = {}; function add(name, value) { if (!name || isEmptyValue(value)) { return; } if (name === 'project_id' && seen.project_id) { return; } if (name === 'visit_date_from' || name === 'visit_date_to') { var rangeEl = form.querySelector('[name="visit_date_range"]'); if (rangeEl && isEmptyValue(rangeEl.value)) { return; } } seen[name] = true; pairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(String(value))); } if (typeof opts.beforeCollect === 'function') { opts.beforeCollect(form, add); } Array.prototype.forEach.call(form.elements, function (el) { if (!el.name || el.disabled) { return; } var tag = el.tagName; var type = (el.type || '').toLowerCase(); if (type === 'checkbox') { if (el.checked) { add(el.name, el.value || '1'); } else if (typeof opts.onUncheckedCheckbox === 'function') { opts.onUncheckedCheckbox(el.name, el, add); } return; } if (type === 'radio') { if (el.checked) { add(el.name, el.value); } return; } if (tag === 'SELECT') { if (el.multiple) { Array.prototype.forEach.call(el.selectedOptions, function (opt) { add(el.name, opt.value); }); } else { add(el.name, el.value); } return; } if (type === 'button' || type === 'submit' || type === 'reset' || type === 'file') { return; } add(el.name, el.value); }); return action + (pairs.length ? '?' + pairs.join('&') : ''); }; window.pmsBindCleanFilterFormSubmit = function (selector, opts) { $(document).on('submit', selector, function (e) { e.preventDefault(); window.location.href = window.pmsBuildCleanGetQuery(this, opts || {}); }); }; }(window));