CodeIgniter_Learner CodeIgniter_Learner - 4 months ago 21
jQuery Question

How to addClass to a cell or td if value from an array of innerHTML present in it?

Recently started learning JQuery and haven't had success on this fo some time now. I am trying to add an array of innerHTML (values from DB) to existing array (something like 'Push') and also give the td's of those array values a class.

My code is:

$('td').click(function() {
$(this).toggleClass('active-select-color');
if($('td').hasClass('active-select-color'))
$('#mark-now').show();
else
$('#mark-now').hide();
});

/* Here I need to add class to "td" containing values from 'PreDates' array */
/* And then push values to array 'selected' */
var PreDates = ["1","2"];
PreDates.adClass('active-select-color');

var selected = [];
var tbl = document.getElementById("calender-table");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
var item = getval(this);
if($(this).hasClass('active-select-color')){
selected.push(item);
} else {
var index = selected.indexOf(item);
selected.splice(index, 1);
}
document.getElementById("dates").value = selected;
}
}
}
function getval(cel) {
return cel.innerHTML;
}


Html table is:

<table border="1" id="calender-table">
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</table>

<input id="dates" type="text" value="" />
<div id="mark-now">Mark As Booked<div>


thanks in advance.

Answer

You can run through all the tds and compare values with array. If found in array then addClass to that td

    /* Here I need to add class to "td" containing values from 'PreDates' array */
    /* And then push values to array 'selected' */
    var PreDates = ["1","2"];
    //PreDates.addClass('active-select-color');
    var selected = [];
   $("#calender-table td").each(function() {
     if (isInArray($(this).html(), PreDates)) {
       $(this).addClass('active-select-color');
       selected.push($(this).html());
     }
     document.getElementById("dates").value = selected;
    });

    function isInArray(value, array) {
      return array.indexOf(value) > -1;
    }