0

I have following code which builds a table from array called 'data'. I would like to add javascript call into my other method called backend_getMovieData, but I dont know how to build a string from movie._id. I'm getting error "Uncaught SyntaxError: Unexpected token } " from my example code.

data.forEach(function(movie) {
    $("#shows").find('tbody')
           .append($('<tr>') 
           .append($('<td>' + movie._id + '</td>'))
           .append($('<td>' + movie.total + ' times</td>'))
           .append($('<td><button class=\'btn btn-success\' onClick=backend_getMovieData(' + movie._id + ');>Show times</button></td>'))); 
});
4
  • Are'nt you missing the quotes around backend_getMovieData(' + movie._id + ');? Commented Apr 6, 2014 at 10:05
  • If I change this line: onClick=backend_getMovieData(' + movie._id + '); into something like: onClick=alert(\'test\'); my code is working Commented Apr 6, 2014 at 10:06
  • @Mino What is that <br/> for ? Commented Apr 6, 2014 at 10:07
  • Oh, they are just some edits on stackoverflow question. I will edit them out. Commented Apr 6, 2014 at 10:09

2 Answers 2

2

I think, your function is expecting a string.

Do this:

data.forEach(function(movie) {
    $("#shows").find('tbody')
           .append($('<tr>') <br />
           .append($('<td>' + movie._id + '</td>'))<br />
           .append($('<td>' + movie.total + ' times</td>'))<br />
           .append($('<td><button class=\'btn btn-success\' onClick="backend_getMovieData(\'' + movie._id + '\')";>Show times</button></td>'))); 
});

You need to wrap it with quotes.

Sign up to request clarification or add additional context in comments.

3 Comments

OK, now im getting into the actual problem. Now its saying Uncaught ReferenceError: Uroot is not defined. And that Uroot is movie._id variables value.
@Mino, I think backend_getMovieData accepts a string. Try my above code.
Yes it actually works! Thank you. I have too many quotes in my javascript code so I was just a bit confused :).
1

JQuery can get it done with a bit more finesse:

$("#shows").on('click', 'button.btn-success', function() { backend_getMovieData(this.id) });

data.forEach(function(movie) {
    $("#shows").find('tbody')
       .append($('<tr>') <br />
       .append($('<td>' + movie._id + '</td>'))<br />
       .append($('<td>' + movie.total + ' times</td>'))<br />
       .append($('<td><button class="btn btn-success" id="' + movie._id + '">Show times</button></td>'))); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.