Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
Changing formData of a form before submit() method is invoked

I need to add some data to a form using FormData so that when the form is submitted this new piece of data is also posted, but I can't get it working. Note that I do not want to use ajax or fetch to send formData since I want the page to redirect user to a different page when he clicks the submit button.

                const myForm = document.querySelector('form');
                myForm.addEventListener('submit', (event) => {
                    event.preventDefault();
                    const formData = new FormData(myForm);
                    formData.append('age', '20');
                    event.target.submit();
                });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As mentioned in comments the best way to do this was to prevent the normal event, submit your own formData object and then redirect by yourself.

var form = document.querySelector("form");
form.addEventListener('submit', e => {
    e.preventDefault()
    // build up formdata
    const formData = new FormData(form);
    formData.append("age", '20');
    const request = new XMLHttpRequest();
    request.open("POST", "submitform.php");    

    // redirect on success
    request.addEventListener('load', function( event ) {
      window.location.replace('/my-locaiton')
    });

    // Do whatever needed on error
    request.addEventListener('error', function( event ) {
      console.log('failed request..')
    });   
    
    request.send(formData);
})
<form id="form" action="POST" target="redirect.html">
    <input type="text" value="somtext">
    <input type="submit">
</form>

If you still want to let the form do the job you could do something like this to prevent the event and then dispatch it again.. You would need to add hidden elements to the form in this case:

const form = document.getElementById('form')
const listener = async (e) => {

    // prevent default action.
    e.preventDefault()

    // only run the listener only once.
    form.removeListener('submit', listener)

    // append actual data..
    const ageInput = document.createElement('input')
    ageInput.style.visibility = 'hidden'
    ageInput.setAttribute('name', 'age')
    ageInput.setAttribute('value', '20')
    form.appendChild(ageInput)

    // dispatch event again!
    e.target.dispatchEvent(e)
}

form.addEventListener('submit', listener)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda