document.getElementById () .value is not working with window.open ()

0

I want to generate a clean print page with some information only. For this I am using the following code (well summarized) in javascript:

function myFunction() {
  var myWindow = window.open(" ", "_self");
  var str1 = "Janela de Impressão";
  var result1 = str1.fontsize(5);
  myWindow.document.write("<strong><center>", result1, "</center></strong>");
  var str2 = "Dados da Impressão";
  var result2 = str2.fontsize(5);
  myWindow.document.write("<strong><br><br>", result2, "</strong>");
  var salario_bruto = document.getElementById("salario").value;
  myWindow.document.write("<strong><br>Salário: </strong>");
  myWindow.document.write(salario_bruto);
}
<div>
  Salário: <input id="salario" name="salario" type="text">
  <button type="button" onclick="myFunction()">Imprimir</button>
</div>

I tested this offline and it worked perfectly. But when I went to the site I clicked on "print" and did not pass the amount of the salary. Any idea? Thanks.

    
asked by anonymous 26.11.2018 / 19:58

2 answers

6

You are changing the window before taking the value of the element. Just get the value before giving window.open :

function myFunction() {
  var salario_bruto = document.getElementById("salario").value;
  var myWindow = window.open(" ", "_self");
  var str1 = "Janela de Impressão";
  var result1 = str1.fontsize(5);
  myWindow.document.write("<strong><center>", result1, "</center></strong>");
  var str2 = "Dados da Impressão";
  var result2 = str2.fontsize(5);
  myWindow.document.write("<strong><br><br>", result2, "</strong>");
  myWindow.document.write("<strong><br>Salário: </strong>");
  myWindow.document.write(salario_bruto);
}
<div>
  Salário: <input id="salario" name="salario" type="text">
  <button type="button" onclick="myFunction()">Imprimir</button>
</div>
    
26.11.2018 / 20:06
3

After opening the window using _self , the code no longer finds the id salario of the page because the page is replaced. Put the line that takes the input id before opening the window in the function:

function myFunction() {
    var salario_bruto = document.getElementById("salario").value; //<< AQUI
    var myWindow = window.open(" ", "_self");
    var str1 = "Janela de Impressão";
    var result1 = str1.fontsize(5);
    myWindow.document.write("<strong><center>",result1, "</center></strong>");
    var str2 = "Dados da Impressão";
    var result2 = str2.fontsize(5);
    myWindow.document.write("<strong><br><br>",result2, "</strong>");
    myWindow.document.write("<strong><br>Salário: </strong>"); myWindow.document.write(salario_bruto);
}
    
26.11.2018 / 20:05