CrazySynthax
CrazySynthax

Reputation: 14988

JavaScript: variable name unresolved

I wrote the following JS code:

function downloadFile(dataItem) {
    ....
}
....
for (var r = 0; r < dataItems.length ; r++) {
    table += '<tr>';
    var listOfAttributes = ['CarModel', 'BusMapping', 'Date_', 'Location_', 'Comments', 'AttackTraffic', 'IsTagged']
    **table +='<td> <a onclick="downloadFile(dataItems[r])" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';**
    for (var c = 0; c < Object.keys(dataItems[0]).length-1 ; c++) {
        table +='<td>' + dataItems[r][listOfAttributes[c]]["S"] +'</td>';
    }
    table+= '</tr>'
}

I get an error for the line:

table +='<td> <a onclick="downloadFile(dataItems[r])" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';

It seems that JS can't resolve the variable 'dataItems' inside the -tag:

<a onclick="downloadFile(dataItems[r])" href="#">.

However, later in the same line, JS resolves successfully the same name for the part:

+ dataItems[r]['FileName']['S'] +

What do you think can be the problem? How can I make dataItems be resolved inside the -tag ?

Upvotes: 0

Views: 485

Answers (3)

Abdul Mateen Mohammed
Abdul Mateen Mohammed

Reputation: 1894

As you're placing a string inside the element's attribute it is not recognized as a JavaScript code or a JavaScript function so place the JavaScript function itself.

So you can do, var anchor = '<a href="#" onclick="' + your_func_here + '"></a>';

A sample example illustrating the problem, in this example if you write the function name as a string in the onclick property the function won't be called.

var container = document.getElementById('container');
var element = document.createElement('a');
element.href = '#';
element.text = 'Fire!';
element.onclick = fire; // this invokes the fire function
// element.onclick = 'fire'; // this won't invoke the fire function
container.appendChild(element);

function fire() {
  console.log('fired');
}
<div id="container">
</div>

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

In this line

<a onclick="downloadFile(dataItems[r])" href="#">

unless dataItems is a global variable, it won't be available to the environment which will make this call downloadFile(dataItems[r]), since onclick event will be invoked in a global scope.

You need to bind the event less intrusively this way

//you need to update the selector as per your markup
document.querySelector ( "tr td a" ).addEventListener( "click", function(){
  downloadFile(dataItems[r]);
})

Upvotes: 0

Maximilian Peters
Maximilian Peters

Reputation: 31659

Your variable is inside a string. Try changing the code to:

table +='<td> <a onclick="' + downloadFile(dataItems[r]) + '" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';**

Upvotes: 3

Related Questions