I
I
It2019-12-01 14:15:08
JavaScript
It, 2019-12-01 14:15:08

How to validate a file download form with minimal JS?

Colleagues, good afternoon.
There was a task, there is a form for downloading a file with required fields. Once the form is filled out correctly, when you click on Download, the contacts should fly to the marketing mail and a window will appear for choosing a location to save the file.
Actually I think how to implement all this with minimal use of JS. the same field validation, albeit at a primitive level, by html itself is perfectly done through required.
Backing on node is written (nodemailer).
Actually questions:
1. How to correctly implement sending contacts on click and at the same time (for the user) start downloading the file?
Here I would like to understand what elements to make type="submit" for the form (button, input, a, maybe 'a' in button, etc.) and what events to hang where. How to style the inactivity of the button is also not entirely clear, the button has the disabled attribute, I tried it through it, but it only works if everything is hung on the button, and if inside 'a', then the download starts anyway.
2. How to redirect to thank-you-page after successful sending of contacts? The usual method is through onclick="window.location.href", but taking into account the downloads, it's somehow difficult. I'm not friends with the node yet, so I need some help.
Separately, this is all done simply, but to combine something correctly is some kind of plug.
If anyone has a piece of ready-made code, then I will be mega grateful, if not, then simply describing the algorithm will be enough.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
EVG, 2019-12-01
@IT_Highlander

1. Use input[type=submit]/button[type=submit]
2. Subscribe to the submit event on the form
3. In the event handler, trigger the file upload with something like this

// https://stackoverflow.com/questions/3916191/download-data-url-file/45905238#45905238?newreg=ddb3c48865d04c319b39f772df762521
function download(dataurl, filename) {
  var a = document.createElement("a");
  a.href = dataurl;
  a.setAttribute("download", filename);
  a.click();
}

3. As for the impossibility of clicking on the submit button, if at least one form field is not valid, then hang something like this:
#someform:invalid [type=submit]{
  pointer-events: none;
  
  /* другие нужные стили, да хоть display: none; */
}

4. If you want to perform a redirect on the back, there is no problem here - just redirect in the back form handler. If you redirect by the client, then cancel the default reaction to the event in the submit handler, collect the data from the form and send it with AJAX to the back, and then redirect to the send page if the data was sent successfully.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question