简体   繁体   中英

Javascript passing variable to inline function in input element

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.

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): 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM