CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-zepto

Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API

Overview
Eval results
Files

forms.mddocs/

Form Handling

Form serialization, validation support, and input value management. Provides comprehensive form processing capabilities for web applications.

Capabilities

Form Serialization

Convert form data to various formats for submission or processing.

/**
 * Serialize form data to URL-encoded string
 * @returns String of serialized form data
 */
$.fn.serialize();

/**
 * Serialize form data to array of name/value objects
 * @returns Array of {name, value} objects
 */
$.fn.serializeArray();

Usage Examples:

// URL-encoded serialization
const formData = $('#myForm').serialize();
// Result: "name=John&email=john%40example.com&age=30"

// Array serialization
const formArray = $('#myForm').serializeArray();
// Result: [
//   {name: 'name', value: 'John'},
//   {name: 'email', value: 'john@example.com'},
//   {name: 'age', value: '30'}
// ]

// Submit form data via Ajax
$('#contactForm').on('submit', function(e) {
  e.preventDefault();
  $.post('/api/contact', $(this).serialize(), function(response) {
    console.log('Form submitted:', response);
  });
});

Form Values

Get and set form input values with type-specific handling.

/**
 * Get or set form element values
 * @param value - Value to set (if provided)
 * @returns Current value (if getting) or collection (if setting)
 */
$.fn.val(value);

Usage Examples:

// Get values
const name = $('#name').val();
const email = $('#email').val();

// Set values
$('#name').val('John Doe');
$('#age').val(25);

// Handle different input types
$('#checkbox').val(['option1', 'option3']); // Check multiple checkboxes
$('#select-multiple').val(['value1', 'value2']); // Select multiple options

// Clear form values
$('#myForm input, #myForm textarea').val('');
$('#myForm select').val(null);

// Get selected values from multi-select
const selectedOptions = $('#multiSelect').val();
// Returns array: ['value1', 'value2']

Form Submission

Handle form submission events with validation and processing.

/**
 * Bind form submission event handler
 * @param callback - Function to call on form submit
 * @returns Original collection
 */
$.fn.submit(callback);

Usage Examples:

// Basic form submission
$('#myForm').submit(function(e) {
  e.preventDefault();
  console.log('Form submitted');
});

// Form validation before submission
$('#registrationForm').submit(function(e) {
  e.preventDefault();
  
  const name = $('#name').val().trim();
  const email = $('#email').val().trim();
  
  if (!name) {
    alert('Name is required');
    return false;
  }
  
  if (!email || !email.includes('@')) {
    alert('Valid email is required');
    return false;
  }
  
  // Submit valid form
  $.post('/register', $(this).serialize(), function(response) {
    window.location = '/welcome';
  });
});

// Programmatically trigger submission
$('#submitButton').click(function() {
  $('#myForm').submit();
});

Form Validation Helpers

Utility patterns for common form validation scenarios.

// Email validation
function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// Required field validation
function validateRequired(selector, message) {
  const value = $(selector).val().trim();
  if (!value) {
    showError(selector, message);
    return false;
  }
  return true;
}

// Show validation errors
function showError(selector, message) {
  $(selector)
    .addClass('error')
    .siblings('.error-message')
    .text(message)
    .show();
}

// Clear validation errors
function clearErrors() {
  $('.error').removeClass('error');
  $('.error-message').hide();
}

// Complete validation example
$('#loginForm').submit(function(e) {
  e.preventDefault();
  clearErrors();
  
  let isValid = true;
  
  isValid &= validateRequired('#username', 'Username is required');
  isValid &= validateRequired('#password', 'Password is required');
  
  const email = $('#email').val();
  if (email && !isValidEmail(email)) {
    showError('#email', 'Please enter a valid email');
    isValid = false;
  }
  
  if (isValid) {
    submitForm($(this));
  }
});

Dynamic Form Handling

Working with dynamically generated form elements.

// Handle dynamically added fields
$('#addField').click(function() {
  const fieldCount = $('.dynamic-field').length;
  const newField = $(`
    <div class="dynamic-field">
      <input type="text" name="field_${fieldCount}" placeholder="Field ${fieldCount + 1}">
      <button type="button" class="remove-field">Remove</button>
    </div>
  `);
  
  $('#dynamicFields').append(newField);
});

// Remove dynamic fields
$(document).on('click', '.remove-field', function() {
  $(this).closest('.dynamic-field').remove();
});

// Serialize dynamic form
$('#dynamicForm').submit(function(e) {
  e.preventDefault();
  
  const formData = {};
  $(this).serializeArray().forEach(function(field) {
    formData[field.name] = field.value;
  });
  
  console.log('Dynamic form data:', formData);
});

File Upload Handling

Working with file inputs and uploads.

// Handle file selection
$('#fileInput').on('change', function() {
  const files = this.files;
  if (files.length > 0) {
    console.log('Selected file:', files[0].name);
    $('#fileName').text(files[0].name);
  }
});

// Upload with FormData
$('#uploadForm').submit(function(e) {
  e.preventDefault();
  
  const formData = new FormData(this);
  
  $.ajax({
    url: '/upload',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
      console.log('Upload successful:', response);
    },
    error: function() {
      console.log('Upload failed');
    }
  });
});

// Drag and drop file upload
$('#dropZone')
  .on('dragover', function(e) {
    e.preventDefault();
    $(this).addClass('drag-over');
  })
  .on('dragleave', function() {
    $(this).removeClass('drag-over');
  })
  .on('drop', function(e) {
    e.preventDefault();
    $(this).removeClass('drag-over');
    
    const files = e.originalEvent.dataTransfer.files;
    handleFileUpload(files);
  });

Form State Management

Tracking form changes and states.

// Track form changes
let formChanged = false;

$('#myForm').on('input change', 'input, textarea, select', function() {
  formChanged = true;
  $('#saveStatus').text('Unsaved changes');
});

// Warn about unsaved changes
$(window).on('beforeunload', function() {
  if (formChanged) {
    return 'You have unsaved changes. Are you sure you want to leave?';
  }
});

// Auto-save functionality
let saveTimeout;
$('#autoSaveForm').on('input change', 'input, textarea, select', function() {
  clearTimeout(saveTimeout);
  saveTimeout = setTimeout(function() {
    autoSave();
  }, 2000); // Save after 2 seconds of inactivity
});

function autoSave() {
  const formData = $('#autoSaveForm').serialize();
  $.post('/autosave', formData, function() {
    $('#saveStatus').text('Saved').fadeIn().delay(2000).fadeOut();
    formChanged = false;
  });
}

Accessibility and UX

Improving form accessibility and user experience.

// Focus management
$('#myForm').on('submit', function(e) {
  const firstError = $('.error').first();
  if (firstError.length) {
    e.preventDefault();
    firstError.focus();
  }
});

// Real-time validation feedback
$('#email').on('blur', function() {
  const email = $(this).val();
  if (email && !isValidEmail(email)) {
    $(this).addClass('invalid').attr('aria-invalid', 'true');
    $('#emailError').text('Please enter a valid email').show();
  } else {
    $(this).removeClass('invalid').attr('aria-invalid', 'false');
    $('#emailError').hide();
  }
});

// Character count for textareas
$('#message').on('input', function() {
  const maxLength = 500;
  const currentLength = $(this).val().length;
  const remaining = maxLength - currentLength;
  
  $('#charCount').text(`${remaining} characters remaining`);
  
  if (remaining < 0) {
    $(this).addClass('over-limit');
  } else {
    $(this).removeClass('over-limit');
  }
});

Install with Tessl CLI

npx tessl i tessl/npm-zepto

docs

advanced-features.md

ajax.md

animation.md

browser-detection.md

callback-management.md

core-dom.md

css-styling.md

data-management.md

enhanced-selectors.md

events.md

forms.md

index.md

mobile-touch.md

stack-operations.md

tile.json