CodeIgniter_Learner CodeIgniter_Learner - 4 months ago 11
Javascript Question

Get array of selected dates from availabilty calendar

I am new and learning jquery from scratch.

I have this availability calendar where multiple dates can be selected. so far I am able to get value of individual cell but not the array of values of total cells selected.



$('td').click(function() {
$(this).toggleClass('active');
});
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 () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}

td {
width: 50px;
height: 50px;
background-color: blue;
color:white;
border: 1px solid black;
}

.active {
background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" id="calender-table" border="1" style="cursor: pointer;">
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>5</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>9</td><td>10</td><td>11</td><td>12</td></tr>
<tr><td>13</td><td>14</td><td>15</td><td>16</td></tr>
</table>





I need some assistance on how to get array of theses multiple selected dates and get as an array so that I can insert them to db using PHP/MySql.

Thanks in advance.

Answer

Save you selected value in an array as selected.push(getval(this) Remove element if class active is not present;

$('td').click(function() {
	$(this).toggleClass('active');
});
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')){ 
   selected.push(item);
           } else {
             var index = selected.indexOf(item);
             selected.splice(index, 1);
           }                                 console.log(selected);}
   
  
   
            }
        }
 function getval(cel) {
  return cel.innerHTML;
  alert(cel.innerHTML);
 }
td {
    width: 50px;
    height: 50px;   
    background-color: blue;
    color:white;
    border: 1px solid black;
}

.active {
    background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" id="calender-table" border="1" style="cursor: pointer;">
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>5</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>9</td><td>10</td><td>11</td><td>12</td></tr>
<tr><td>13</td><td>14</td><td>15</td><td>16</td></tr>
</table>

Comments