Skip to content

Instantly share code, notes, and snippets.

@MohamedLamineAllal
Created November 18, 2018 23:19
Show Gist options
  • Save MohamedLamineAllal/e4e8e4afa590ddf3b09cd80c8b9162d2 to your computer and use it in GitHub Desktop.
Save MohamedLamineAllal/e4e8e4afa590ddf3b09cd80c8b9162d2 to your computer and use it in GitHub Desktop.
Add data to from function with overiding and nice call for form
function addDataToForm(form, data) {
if(typeof form === 'string') {
if(form[0] === '#') form = form.slice(1);
form = document.getElementById(form);
}
var keys = Object.keys(data);
var name;
var value;
var input;
for (var i = 0; i < keys.length; i++) {
name = keys[i];
// removing the inputs with the name if already exists [overide]
console.log(form);
Array.prototype.forEach.call(form.elements, function (inpt) {
if(inpt.name === name) {
inpt.parentNode.removeChild(inpt);
}
});
value = data[name];
input = document.createElement('input');
input.setAttribute('name', name);
input.setAttribute('value', value);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
return form;
}
//Use :
addDataToForm(form, {
'uri': window.location.href,
'kpi_val': 150,
//...
});
//you can use it like that too
var form = addDataToForm('myFormId', {
'uri': window.location.href,
'kpi_val': 150,
//...
});
//you can add # if you like too ("#myformid").
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment