Dean Byron Dean Byron - 6 months ago 14
Javascript Question

Button doesn't call script - onclick method

For some reason my button isn't calling the script and Chrome's Console replies with the error "Unexpected token }"

Here is the script:

<script type="text/javascript" src="js/jquery-1.10.2.min.js">

function printContent(el){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innderHTML = printcontent;
window.print();
document.body.innderHTML = restorepage;
}

</script>


Here is my button:

echo '<center>
<button onclick="printContent("printable");" class="btn btn-default">
<span class="glyphicon glyphicon-print"></span> &nbsp; Print
</button>
</center> ';


The reason for the echo is cause I am using PhP to call the button depending on the situation.

The div it's suppose to be printing looks something like this:

<div class="container" id="printable">

Answer

You need to close the <script> tag that imports jQuery and create a new <script> tag in which you can put your own JavaScript, like this:

<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script>
  function printContent(el) {
    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById(el).innerHTML;
    document.body.innerHTML = printcontent;
    window.print();
    document.body.innerHTML = restorepage;
  }
</script>

As mentioned before, you made a typo while typing innerHTML, which I fixed in the above code, and an error because you're using double quotes twice in the onclick, which you can fix by changing your echo to this:

echo '<center>
       <button onclick="printContent(\'printable\');" class="btn btn-default">
        <span class="glyphicon glyphicon-print"></span> &nbsp; Print
       </button>
      </center> ';