Ibanez1408 Ibanez1408 - 4 years ago 159
Javascript Question

Get value if td contains specific text in jquery

I have this table with all the leaves of employee at a certain column.

Date Applied Leave Type Days From Date To Date Status
2017-01-01 Vacation Leave 1 2017-01-02 2017-01-03 No Action
2017-02-01 Sick Leave 1 2017-02-02 2017-02-03 Approved
2017-03-01 Vacation Leave 2 2017-03-02 2017-03-03 Approved


Using jquery or just core javascript, how do I get the number of days for the "Vacation Leave" and number of days for the "Sick Leave" if the were approved.

This is how I get the table

function writeResult(res){
var p = document.getElementById("write_result");
p.innerHTML = "";

var addHtml = "<table align=\"center\" border=\"1\" cellspacing=\"0\" style=\"font-weight:regular;\">";
addHtml += "<tr>";
addHtml += "<th>Date Applied</th><th>Leave Type</th><th>Days</th><th>From Date</th><th>To Date</th><th>Status</th>";
for(var i=0;i<res.length;i++){
addHtml += "<tr>";
addHtml += "<td>"+ changeDateFormat(res[i][0]) +"</td>";
addHtml += "<td>"+ res[i][1] +"</td>";
addHtml += "<td>"+ res[i][2] +"</td>";
addHtml += "<td>"+ changeDateFormat(res[i][3]) +"</td>";
addHtml += "<td>"+ changeDateFormat(res[i][4]) +"</td>";
addHtml += "<td>"+ res[i][5] +"</td>";
addHtml += "</tr>";
}
addHtml += "</tr>";
addHtml += "</table>"
addHtml += "<div>";
addHtml += "<table>";
addHtml += "<tr>";
addHtml += "<th>Vacation Leaves: &nbsp;</th><td id='vacation_leaves'>0</td>";
addHtml += "<th>&nbsp; &nbsp; Sick Leaves: &nbsp;</th><td id='sick_leaves'>1</td>";
addHtml += "</tr>"
addHtml += "</table>";
addHtml += "</div>";
p.innerHTML = addHtml;
}


Example:

Vacation Leave = 2
Sick Leave = 1

Thank you.

Answer Source

Add an id to your table like <table id="leaveTable"> then you could use something like this:

var approvedVacLeave = 0;
var approvedSickLeave = 0;
$("#leaveTable tr").each(function (){
    var leaveType = $(this).find("td:nth-child(2)").text();
    var numDays = +$(this).find("td:nth-child(3)").text();
    var status = $(this).find("td:nth-child(6)").text();
    if (status == "Approved") {
        if (leaveType == "Vacation Leave") {
            approvedVacLeave += numDays;
        }
        else if (leaveType == "Sick Leave") {
            approvedSickLeave += numDays;
        }
    }
});
console.log("Vacation days = " + approvedVacLeave + " and sick days = " + approvedSickLeave);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download