Как создать кнопку, которая одновременно отправляет форму и загружает PDF-файл?

Опубликовано: 1 Декабря, 2021

Не существует прямого метода одновременной загрузки и отправки формы, но мы можем выполнить эту задачу, если мы будем контролировать отправку формы и, нажав кнопку отправки формы, мы сначала запускаем загрузку PDF-файла, а затем отправляем форму. Итак, подходы, которые мы можем использовать для этого, обсуждаются ниже:

Подход 1: Создание кнопки формы отправки вне формы:

  • Во-первых, создайте форму со скрытой кнопкой отправки.
  • Укажите идентификатор кнопке отправки формы, чтобы получить к ней доступ с помощью JS.
  • Создайте кнопку вне формы и присвойте ей уникальный идентификатор для доступа к ней.
  • Создайте тег привязки, используя свойство createElement и назначив ему атрибут href и download.
  • После этого мы просто вызываем событие нажатия кнопки отправки при нажатии кнопки загрузки, используя свойство onClick.

HTML

<!DOCTYPE html>
< html lang = "en" >
< head >
< style >
form {
color: green;
}
</ style >
</ head >
< body >
<!-- GFG is the name of the file to be downloaded-->
<!-- In order to run the code, the location of the
file "GFG.pdf" needs to be changed to your local
directory, both the HTML and downloadable file
needs to be present in the same directory -->
< form method = "post" >
< label for = "username" >GFG Username</ label >
< input type = "text" name = "username" />
< input type = "submit" id = "submit-form"
value = "submit" hidden />
</ form >
< button id = "download-pdf" >Submit</ button >
< script >
const downloadPdf = document
.querySelector("#download-pdf");
const submitForm = document
.querySelector("#submit-form");
downloadPdf.addEventListener("click", () => {
// Creating the element anchor that
// will download pdf
let element = document.createElement("a");
element.href = "./GFG.pdf";
element.download = "GFG.pdf";
// Adding the element to body
document.documentElement.appendChild(element);
// Above code is equivalent to
// < a href = "path of file" к = "file name" > "path of file" download = "file name" >
// onClick property, to trigger download
element.click();
// Removing the element from body
document.documentElement.removeChild(element);
// onClick property, to trigger submit form
submitForm.click();
});
</ script >
</ body >
</ html >

Выход:

При отправке:

Подход 2: Отключить отправку при отправке: более простым методом может быть отключение отправки при нажатии кнопки формы отправки и отправка вручную при вызове функции, которая сначала загружает PDF, а затем отправляет форму.

  • Во-первых, создайте форму с атрибутом onsubmit, установленным на 'return: false;', что фактически предотвращает отправку формы при нажатии кнопки отправки.
  • Создайте тег привязки, используя свойство createElement и назначив ему атрибут href и download.
  • После этого мы просто вызываем событие отправки в форме, чтобы отправить его, после запуска загрузки из созданного нами элемента.

HTML

<!DOCTYPE html>
< html >
< head >
< style >
form {
color: green;
}
</ style >
</ head >
< body >
<!-- GFG is the name of the file to be downloaded-->
<!-- In order to run the code, the location of the
file "GFG.pdf" needs to be changed to your local
directory, both the HTML and downloadable file
needs to be present in the same directory -->
< form id = "my-form" onsubmit = "return: false;" >
< label for = "username" >GFG username</ label >
< input type = "text" name = "username" />
< input type = "submit" id = "submit-form"
value = "Submit" />
</ form >
< script >
const myForm = document
.querySelector("#my-form");
const submitForm = document
.querySelector("#submit-form");
submitForm.addEventListener("click", () => {
// Creating element to download pdf
var element = document.createElement('a');
// Setting the path to the pdf file
element.href = 'GFG.pdf';
// Name to display as download
element.download = 'GFG.pdf';
// Adding element to the body
document.documentElement.appendChild(element);
// Above code is quivalent to
// < a href = "path to file" download = "download name" />
// Trigger the file download
element.click();
// Remove the element from the body
document.documentElement.remove(element);
// Submit event, to submit the form
myForm.submit();
});
</ script >
</ body >
</ html >

Выход:

При отправке: