Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error with jQuery append

My code is as follows:

        <script>
        var i = 2;
        $("document").ready(function(){
            $("#newrow").click(function(){
                $("#maintable").append('<tr>
                                        <td><input type="text" name="dept_" + i size="5" maxlength="5" /></td>
                                        <td><input type="text" name="hours_" + i size="5" maxlength="1" /></td>
                                    </tr>');
            });
            i = i + 1;
        });
    </script>

Whenever I run it, JavaScript gives me an "Uncaught SyntaxError: Unexpected Token ILLEGAL" on the $("#maintable").append line.

For the life of me, I can't figure out what the syntax error is.

It's not a problem with the actual element being appended, because I tried just '<td></td>' as well and that got the same error.

like image 322
Andrew Latham Avatar asked Mar 31 '12 00:03

Andrew Latham


2 Answers

You can't break a string over multiples lines without special treatment. Either put it all on one line, or escape the newlines with backslashes:

'<tr>\
     <td><input type="text" name="dept_"' + i + ' size="5" maxlength="5" /></td>\
     <td><input type="text" name="hours_"' + i + ' size="5" maxlength="1" /></td>\
</tr>'
like image 148
Dennis Avatar answered Oct 16 '22 23:10

Dennis


<script>
    var i = 2;
    $(document).ready(function(){
        $("#newrow").click(function(){
            var html = '<tr>';
                html += '<td><input type="text" name="dept_"'+i+' size="5" maxlength="5" /></td>';
                html += '<td><input type="text" name="hours_"'+i+' size="5" maxlength="1" /></td>';
                html += '</tr>'
            $("#maintable").append(html);
        });
        i++;
    });
</script>

document does not have quotes, right now your "ready" function does not work! The variable "i" is not added at all! A string can't be divided over multiple lines unless you use newlines, add to a variable, or something similar.

like image 29
adeneo Avatar answered Oct 17 '22 00:10

adeneo