Modelesq Modelesq - 5 months ago 21
Javascript Question

remove button input from form.elements array javascript

I have a form, and I'm grabbing all input elements inside of it and place them into an their keys and values into an object (That works)... However I wan't to filter out the un needed button... How can I remove it/ ignore it?

if I console.log form.elements it returns:

[input#first_name.input-text, input#last_name.input-text, input#username.input-text, input#email.input-text,
button#submit.btn ...]

const formatData = {};
const form = document.getElementById('signup');
console.log(form.elements);

for (let i = 1; i < myForm.elements.length; i++) {
// check if button and remove / ignore
if (form[i] === 'button') { // this doesn't work
delete form[i];
}
const key = form.elements[i].name;
const value = form.elements[i].value;
formatData[key] = value;


How can I make sure button isn't included? :\ (this is written in jsx syntax)

Answer

You can filter form.elements by tagName.

const formatData = {};
const form = document.getElementById('signup');

[].slice.apply( form.elements ) // convert HTMLFormControlsCollection to Array
  .filter(( el ) => el.tagName !== 'BUTTON') // filter out all <button> elements
  .forEach(function ( el ) {
      formatData[ el.name ] = el.value; // add key / value to formatData object
  });

OR, if you prefer the for loop:

const formatData = {};
const form = document.getElementById('signup');

for (let i = 0, n = form.elements.length; i < n; i++) {
  if (form.elements[i].tagName === 'BUTTON') continue;

  formatData[ form.elements[i].name ] = form.elements[i].value;
}
Comments