Search code examples
javascriptloopsbuttonclick

Unexpected identifier in Javascript for loop


This seems to work 75% of the time and the modal function executes with the parameters available, but every few buttons in the table I'll get a Uncaught SyntaxError: Unexpected identifier. Does this have to do with inproper closure? My google searches landed on that as a potential issue but I was unable to implement any of the solutions into my current method here.

html += '<thead><th>Question</th><th>Answer 1</th><th>Answer 2</th><th>Answer 3</th><th>Answer 4</th></thead>';

        for (var i = 0; i < questions.length; i++) {

            question = questions[i].question;
            questionTitle = question.q;
            answer1title = question.a1;
            answer2title = question.a2;

            html += '<tr><td class="question"><b>'
             + question.q
             + '</b></td><td class="answer1">'
             + question.a1
             + '</td><td class="answer2">'
             + question.a2
             + '</td><td class="answer3">'
             + question.a3
             + '</td><td class="answer4">'
             + question.a4
             + '</td><td class="edit">'
             + '<button onclick="openQuestionModal(\''+questionTitle+'\', \''+answer1title+'\', \''+answer2title+'\')" class="btn btn-small btn-primary" id="questionEdit" type="button">Edit</button>'
             + '</td></tr>';   

        }

        $('#questionsTable').append(html); 

Solution

  • The problem is that any of questionTitle, answer1title, or answer2title may have a single quote in their values, which breaks the string concatenation you are attempting. You need to replace all occurrences of a single quote with an escaped single quote. So something like this:

    http://jsfiddle.net/ZYnfc/2/

    $(document).ready(function () {
        var par = "I'm the problem";
        var replacer = new RegExp("'", "g");
        var new_btn = $('<button onclick="clicker(\'' + par.replace(replacer, "\\'") + '\');">ASDF</button>');
        $("#main").append(new_btn);
    });
    
    function clicker(param) {
        alert(param);
    }
    

    You'll have to take my example and apply it to your actual code, but the main point is the use of the replace method and the replacer regex for each of your variables you're concatenating in the function call.

    There are better ways to append HTML to an area, especially when it comes to a table. And I would suggest binding events with jQuery, not inline. That's a different topic and is unrelated to your problem, although it could've helped avoid it in the first place.