How to force dowload a pdf?

Asked

Viewed 983 times

4

I have a PHP and HTML application of a registration form, as I do to download a select as an example: By clicking yes, it downloads according to a link that makes this (download) in pdf. Follow the print for more information and the script as well.`

<script>
  function carregaPdf(){
     if(document.getElementById("alojamento").value == "SIM"){
        window.open("http://www.ibc.gov.br/media/common/regulamento_interno_do_alojamento_ibc.pdf");
      }
   }
</script>

<div class="form-group">
    <label class="col-sm-2 control-label">Alojamento</label>
    <div class="col-sm-10">
        <select onchange="carregaPdf()" class="form-control" name="alojamento" id="alojamento" style="width:100px; padding:2px;" required>
            <option value="">Selecione</option>
            <option value="SIM">SIM</option>
            <option value="NAO">NÃO</option>
        </select>
    </div>
</div>

My question is that you are opening a window with the pdf, I want you to force to download the pdf file as soon as you click yes, someone can help me?

  • Dude, to help you. Always post the code here instead of in an external environment. Actually you can do this, but put the code here and if you want you can leave it somewhere else like Pastebin, Codepen or Jsfiddle. Now... this you will do with JS. By selecting the option, you can make a change in select.

  • I posted on Pastebin

  • @Carloseduardoferreira here we do not put the question as solved. There is a visa to mark the answer as certain, if any.

2 answers

1

You can create a change function to receive the value of the combobox and make an option check. If you choose yes, redirect the user to the file link.

$(document).ready(function(){
   $('select').on('change', function(){
      var valor = $(this).val();
     
      if(valor == 1){
         document.location.href = 'link-para-download.php'; // ou .pdf 
      }
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="0">Selecione a opção</option>
  <option value="1">Sim</option>
  <option value="2">Não</option>
</select>

  • You can, but put it here... If you have the option to put it here, put it here. There are people who do not have access to external sites, only to Stack.

0

See the attribute download of HTML element a:

<a href="pdfs/regulamento_interno_do_alojamento_ibc.pdf" download>Descarregue o regulamento</a>

I recommend generating a link valid for user after acceptance, instead of opening a window.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.