Getting Form content as JSON

JavaScript

To gather all information a Form contains with JavaScript could be easy.
Most browsers provide an object that handles it.

var formData = new FormData( document.getElementById('form' ) ) var data = formData.entries()

Unfortunately this object is not cross browser that's why we have to use this alternative.
It's a FormData alternative and should work the same.

var elements = document.getElementById('form' ).elements var data = {} var add = function(name, value) { if(!value) value = '' // if it's only one, we must use that element // if there are mutliple, we add them to an array if (!data[name]) data[name] = value else if(data[name].constructor === Array) { data[name].push(value) } else data[name] = [data[name], value] } for (var i = 0; i < elements.length; i++) { var item = elements.item(i) if (!item.name || item.disabled) continue if (!item.type) add(item.name,item.value) else if (item.type == 'checkbox' || item.type == 'radio') { if (item.checked) add(item.name,item.value) } else if (item.type == 'select-multiple') { for (var j = 0, op; op = item.options[j++];) if(op.selected) add(item.name,op.value) } else if (item.type == 'file') add(item.name,item.files) else if (item.type == 'submit') { if (item === document.activeElement) add(item.name,item.value) } else add(item.name,item.value) }

Reference

FormData.entries() developer.mozilla.org

History Mar 12, 2017