Reputation: 697
I have the following code:
$(document).ready(function () {
debugger;
// Empty aarray to store list of headings
var tableHeadings = [];
// For each heading present add it to the array (ordered)
$('#AdvancedTable thead > tr > th').each(function () {
//console.log($(this).text());
$(tableHeadings).add($(this).text());
});
// For each row in the table, add the heading text to the start of each cell
$('#AdvancedTable tbody > tr > td').each(function (index) {
$(this).prepend('<span class="visible-xs">' + tableHeadings[index] + '</span>');
})
});
However, one of my table headings I am storing values from contains the text "Length (L1)". I get the following error in my console:
Uncaught Error: Syntax error, recognised expression: Length (L1)
I understand the basics that this is caused by there being issues with text passing something with brackets in it, but would like to know the details of why this happens and a hint as to how I can solve this/best practices to avoid an error like this.
Upvotes: 0
Views: 66
Reputation:
tableHeadings is a simple array, so you can use push function to add value:
$(document).ready(function () {
let tableHeadings = [];
$('#AdvancedTable thead > tr > th').each( (index, item) => {
tableHeadings.push($(item).text())
});
$('#AdvancedTable tbody > tr > td').each( (index, item) => {
$(item).prepend('<span class="visible-xs">' + tableHeadings[index] + '</span>');
})
});
Upvotes: 1
Reputation: 24965
Use map
instead of each
.
// Empty aarray to store list of headings
var tableHeadings = $('#AdvancedTable thead > tr > th').map(function () {
return this.innerHTML;
}).get();
You are creating an empty array, iterating over elements, and adding them to an array. This is essentially reinventing the wheel for what map already does.
Upvotes: 3
Reputation: 359
Not sure why you're using JQuery to add an item to a list; perhaps try:
tableHeadings.push($(this).text());
instead of the original line:
$(tableHeadings).add($(this).text());
Upvotes: 0
Reputation: 876
$(tableHeadings).add($(this).text());
need to be
tableHeadings.push($(this).text())
Upvotes: 0