← back to Butlr

public/js/form.js

33 lines

// Form helpers — category radio click-through, goal placeholder presets
(function () {
  // Visual feedback when a category radio is selected (CSS .selected toggle).
  document.querySelectorAll('.category-pick-card').forEach(label => {
    label.addEventListener('click', () => {
      document.querySelectorAll('.category-pick-card.selected').forEach(el => el.classList.remove('selected'));
      label.classList.add('selected');
      const id = label.querySelector('input[type=radio]')?.value;
      if (!id) return;
      fetch('/api/category/' + encodeURIComponent(id))
        .then(r => r.ok ? r.json() : null)
        .then(j => {
          if (!j || !j.category) return;
          const goalEl = document.querySelector('textarea[name=goal]');
          // Replace placeholder + value if the user hasn't typed anything yet
          if (goalEl && !goalEl.value && j.category.defaultGoal) {
            goalEl.placeholder = j.category.defaultGoal;
          }
        })
        .catch(() => { /* non-fatal */ });
    });
  });

  // Phone-number formatting (US) on blur
  document.querySelectorAll('input[type=tel]').forEach(el => {
    el.addEventListener('blur', () => {
      const digits = el.value.replace(/\D/g, '');
      if (digits.length === 10) el.value = `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6)}`;
      else if (digits.length === 11 && digits[0] === '1') el.value = `+1 (${digits.slice(1,4)}) ${digits.slice(4,7)}-${digits.slice(7)}`;
    });
  });
})();