Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do spaces affect JavaScript in my html elements?

I am iterating through a JSON object and I am getting the data and created a row in a table. However, when I don't put spaces when I'm appending the rows i.e. I make it just one line, it works.

for(var i in data.students)
{    
    table += 
        '<tr><td id="studentName">' + data.students[i].firstname + ' ' + data.students[i].lastname +'</td><td><select class="attendSelect" id="studentSelect'+ data.students[i].lastname +'"><option value="Attended">Attended</option><option value="Excused">Excused</option><option value="Absent">Did not Attend</option></select></td></tr>';
}

However, when I try to make it look tidy by indenting and adding spaces. It breaks up. I don't understand!

for(var i in data.students)
{    
    table += 
        '<tr>
            <td id="studentName">' + data.students[i].firstname + ' ' + data.students[i].lastname +'</td>
            <td>
                <select class="attendSelect" id="studentSelect'+ data.students[i].lastname +'">
                    <option value="Attended">Attended</option>
                    <option value="Excused">Excused</option>
                    <option value="Absent">Did not Attend</option>
                </select>
            </td>
        </tr>';
}
like image 356
Johnathan Au Avatar asked Mar 19 '26 21:03

Johnathan Au


2 Answers

You can't just add line returns inside of strings. You can do this one of two ways:

var mystring = "this" + 
               "is multi" + 
               "line";

or

var mystring = "this \ 
               is multi \
               line";

Note that these two string are not equal. The first example has no space between the lines. The 2nd example includes all of that white-space at the beginnings of the lines in the string.

like image 101
James Montagne Avatar answered Mar 21 '26 10:03

James Montagne


Thats the way the just time compiler thinks.

Add a \ at the end of each line within the " string "

like image 38
Har Avatar answered Mar 21 '26 09:03

Har



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!