0

I am trying to pass an object, totalArray into an input element, id=fullReport so that I will be able to use the variable totalArray within a function: printFullReport.

The input element is concatenated in a string so that it can be eventually created into a table.

I am unable to pass totalArrays into onclick="printFullReport('+ totalArray+ ')"> possibly due the string concatenation, in my console I recieve: "Uncaught SyntaxError: Unexpected identifier" which implies a missing ; or ' but it appears to fine to me.

So this is my initial attempt:

<script type="text/javascript">
console.log(totalArray); //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
var str = "";
str += '<td>
<input id ="fullReport"  
class="button" 
type="button" 
value="Full Report" 
    onclick="printFullReport('+ totalArray+ ')">
    TOTAL (GBP):</td>';
</script>

this is my second attempt after reading and following the top answer: Inline onclick JavaScript variable

<script type="text/javascript">
var str = "";
console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};

function init(){
    document.getElementById('fullReport').onclick=function(){
        printFullReport(totalArray);
    };
}
window.onload=init;

str += '<td><input id ="fullReport"  class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>

but now this is returning: Uncaught ReferenceError: init is not defined.

I am possibly not understanding scope when having html elements in javascript strings.

hello world
  • 306
  • 1
  • 6
  • 28

1 Answers1

1

For second attempt, you are missing the closing double-quote "

<script type="text/javascript">

And you need to assign the onclick from where the totalArray is accessible. (now that you clarified in comments that totalArray is not globally scoped.)

Demo

<script type="text/javascript">
var str = "";
totalArray ={ "1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};

//console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};

function init(){
    document.getElementById('fullReport').onclick=function(){
        printFullReport(totalArray);
    };
}
window.onload=init;

str += '<td><input id ="fullReport"  class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>

<input id ="fullReport"  class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):
gurvinder372
  • 66,980
  • 10
  • 72
  • 94