0

I have a simple form contain an input file for uploading file. now I want whenever user select a file , form submitted automatically . this is my html codes :

<form action="/upload" id="upload_form" name="upload_form" enctype="multipart/form-data" method="post">
    <input type="file" name="user_file" id="user_file">
    <input type="submit" value="Send Form">
</form>

And this is javascript codes:

const upload_form = document.getElementById('upload_form')
const user_file = document.getElementById('user_file')

upload_form.addEventListener('submit',e=>{
    alert('Form Submitted...')

    e.preventDefault()
})
user_file.addEventListener('change', () => {
    alert('user file changed...')
    upload_form.submit()
})

Note that when I use Submit button to send form Form Submitted... is shown but that not work after input file is changed.

Ahmad Badpey
  • 6,348
  • 16
  • 93
  • 159
  • 5
    _"does not work"_ is not sufficient detail. What happened when you tried? Did you get an error? What behaviour are you expecting? What behaviour did you observe? – Wyck Feb 01 '23 at 14:56
  • in fact `Form Submitted...` message does not show. that means whole of callback function that I take to submit does not run – Ahmad Badpey Feb 01 '23 at 14:58
  • So the form does submit, it's just that the submit event listener doesn't get triggered. That is the expected behaviour. – Quentin Feb 01 '23 at 14:59
  • ok how can I solve the problem ? – Ahmad Badpey Feb 01 '23 at 15:05
  • When does your code run?If it runs before the DOM loads, then those elements don't exist and you can't add event listeners to them. – mykaf Feb 01 '23 at 15:06
  • those run after DOM loads. because I inserted script tag at the end html file – Ahmad Badpey Feb 01 '23 at 15:08
  • 1
    see the [docs on submit](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit). `submit()` does not raise a submit event, however, you can call `requestSubmit()` instead which will have the same effect as clicking the form button – Sleepwalker Feb 01 '23 at 15:12
  • Yes , that's right... – Ahmad Badpey Feb 01 '23 at 15:13

0 Answers0