Raafat Hamzeh
Raafat Hamzeh

Reputation: 25

Rails: How to call a Javascript function from HTML in render :pdf

I need to show a text result of an amount, and for this I'm using a javascript function "toWords". This function is working great when I use onInput or onClick, but I need to call this function when the document opens. So this is what I tried:

  <div class="label-field-pair3-text-area">
    <p id="demo"></p>

    </div>


<script type='text/javascript'>



document.getElementById("demo").innerHTML = window.toWords("<%= @amount.to_f %>"); 

..... </script>

But this doesn't work. I also tried this:

 j(document).ready( function(){ text_amount();});
 function text_amount(){
  var i= getElementbyId('payment_text');
  i.val(toWords("<%= @amount.to_f %>"));}

And this:

   <div class="label-field-pair3-text-area" id='payment_text' onload = "text_amount(150)">

But none of this worked, and nothing is displayed.

UPDATE: When I removed render :pdf from controller, it worked. So the problem is in running this function onLoad upon rendering my PDF file.

Upvotes: 1

Views: 1218

Answers (3)

user3640056
user3640056

Reputation: 732

I'm also having problems with render :pdf, so I'm using this instead:

    <%= link_to t('print'), "#", {:class  => 'grey-button-large themed_bg themed-dark-hover-background',  :href=>'javascript:printReceipt()'}%>

Then in script:

 function printReceipt()
{ 
  //$('#page-yield').printElement(); 
   var divName = "page-yield";
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;

    window.print();

    document.body.innerHTML = originalContents;
}

This is a temporary solution that will open your file as a page and when the user clicks on print, it gets printed.

However, I advice you to check PRAWN:

http://www.sitepoint.com/pdf-generation-rails/

How to render format in pdf in rails

Upvotes: 0

Fallflame
Fallflame

Reputation: 221

Check if the method toWords is loaded by

console.log(window.toWords);

before you use it

The html page load the script in sequence, if you add the method after you use it, it is undefined.

Upvotes: 0

Max Williams
Max Williams

Reputation: 32945

It looks like you have a mix of jquery and regular js there: you define i with getElementById and then call the jquery object function val() on it. val() needs to be called on a jquery object, which i is not. Try this instead:

 function text_amount(){
   var i = $('#payment_text');
   i.val(toWords("<%= @amount.to_f %>"));
 }

or, more simply,

 function text_amount(){
   $('#payment_text').val(toWords("<%= @amount.to_f %>"));
 }

Upvotes: 1

Related Questions