// Progressive enhancement for the notices admin form. // // Without JavaScript the server-rendered checkbox removes a row and the // single blank row is how you add one. This script only makes those two // actions interactive: it turns the checkbox into a Remove button and // clones the blank row for an Add button. It never changes what the form // submits, so a JS-on submit and a JS-off submit build the same document. (function () { 'use strict'; var form = document.querySelector('form.admin-form'); if (!form) return; document.body.classList.add('has-js'); var tbody = form.querySelector('tbody'); if (!tbody) return; // Capture the server-rendered blank "add" row before anyone types in it, // and use its markup as the template for rows the Add button creates. var seed = tbody.lastElementChild; if (!seed) return; var seedHTML = seed.outerHTML; function enhance(row) { var cell = row.querySelector('.admin-del'); if (!cell || cell.dataset.enhanced) return; cell.dataset.enhanced = '1'; // The checkbox stays in the DOM (hidden) so a form that is somehow // submitted without JS still means what it did before. var box = cell.querySelector('input[type=checkbox]'); if (box) box.hidden = true; var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'chip row-remove'; btn.textContent = 'Remove'; btn.addEventListener('click', function () { row.parentNode.removeChild(row); }); cell.appendChild(btn); } function addRow() { var wrap = document.createElement('tbody'); wrap.innerHTML = seedHTML; var row = wrap.firstElementChild; row.querySelectorAll('input, textarea').forEach(function (el) { if (el.type === 'checkbox') el.checked = false; else el.value = ''; }); tbody.appendChild(row); enhance(row); } Array.prototype.forEach.call(tbody.querySelectorAll('tr'), enhance); var add = document.getElementById('add-notice'); if (add) add.addEventListener('click', addRow); })();