form serialize javascript (no framework)

后端 未结 23 1545
一生所求
一生所求 2020-11-22 16:07

Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialized version?

23条回答
  •  难免孤独
    2020-11-22 16:55

    For modern browsers only

    If you target browsers that support the URLSearchParams API (most recent browsers) and FormData(formElement) constructor (most recent browsers), use this:

    new URLSearchParams(new FormData(formElement)).toString()
    

    Everywhere except IE

    For browsers that support URLSearchParams but not the FormData(formElement) constructor, use this FormData polyfill and this code (works everywhere except IE):

    new URLSearchParams(Array.from(new FormData(formElement))).toString()
    

    Example

    var form = document.querySelector('form');
    var out = document.querySelector('output');
    
    function updateResult() {
      try {
        out.textContent = new URLSearchParams(Array.from(new FormData(form)));
        out.className = '';
      } catch (e) {
        out.textContent = e;
        out.className = 'error';
      }
    }
    
    updateResult();
    form.addEventListener('input', updateResult);
    body { font-family: Arial, sans-serif; display: flex; flex-wrap: wrap; }
    input[type="text"] { margin-left: 6px; max-width: 30px; }
    label + label { margin-left: 10px; }
    output { font-family: monospace; }
    .error { color: #c00; }
    div { margin-right: 30px; }
    
    
    

    Form

    Query string

    Compatible with IE 10

    For even older browsers (e.g. IE 10), use the FormData polyfill, an Array.from polyfill if necessary and this code:

    Array.from(
      new FormData(formElement),
      e => e.map(encodeURIComponent).join('=')
    ).join('&')
    

提交回复
热议问题