Last active
December 19, 2021 07:34
-
-
Save ruandre/6a8106ed76ea0bc2701ececd6923e7c6 to your computer and use it in GitHub Desktop.
Create and submit form programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// useful when a 'followed' redirect needs to happen, etc. | |
// https://github.com/insin/get-form-data | |
function $forEach(arr, cb) { | |
var arrLen = arr.length | |
for (var i = 0; i < arrLen; i++) cb(arr[i]) | |
} | |
function $form(action, method, fields) { | |
var form = document.createElement('form') | |
form.setAttribute('hidden', 'true') | |
form.setAttribute('action', action) | |
form.setAttribute('method', method) | |
$forEach(fields, function (field) { | |
var tmp = document.createElement('input') | |
tmp.setAttribute('type', field.type || 'text') | |
tmp.setAttribute('name', field.name || '') | |
tmp.setAttribute('value', field.value || '') | |
form.appendChild(tmp) | |
}) | |
document.body.appendChild(form) | |
console.log(getFormData(form)) // debug | |
form.submit() | |
} | |
// usage: | |
$form('/', 'POST', [ | |
{ name: 'one', value: 1 }, | |
{ name: 'two', value: 2 }, | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment