محاسبه آنلاین معدل

محاسبه آنلاین معدل با قابلیت خروجی به اکسل به صورت متن باز تولید شده توسط جاوا اسکریپت (حمزه سرلک)

by hamix

HTML

نام درس  
<input type="text" style="width:70px" id="name" />  
نمره *
<input type="text" style="width:70px" id="score" />    
تعداد واحد *
<input type="text" style="width:70px" id="unitCount" />  
<br/>
<br/>
<input type="button" id="btnAdd" value="افزودن درس" />
<input type="button" id="btnCal" value="محاسبه" />
<input type="button" id="btnClear" value="پاکسازی" />
<br/>
<br/>
<table id="data" style="width:100%">
    <tr style="background-color: #00ff00">
        <td>نام درس</td>
        <td>نمره</td>
        <td>تعداد واحد</td>
    </tr>
</table>
<br/>
<a href="#" class="export">خروجی به اکسل</a>

CSS

body {
    direction:rtl;
    font: 12px tahoma;
}
.res{
    background-color: red
}

a.export, a.export:visited {
    text-decoration: none;
    color:#000;
    background-color:#ddd;
    border: 1px solid #ccc;
    padding:8px;
}

JavaScript

$(document).ready(

function () {
    $("#btnCal").click(function () {
        if($(".row").length==0) return;
        var res=$("<tr class='resRow'><td class='res'>معدل</td><td class='res' colspan='2'>"+ getAvg()+"</td></tr>")
        $("#data").find(".resRow").remove();
        $("#data").append(res);
    });
    $("#btnClear").click(function () {
        $(".row , .resRow").remove();
    });
    $(".export").on('click', function (event) {
        exportTableToCSV.apply(this, [$('#data>table'), 'export.csv']);
    });
    
    $("#btnAdd").click(function () {
        var name = $("#name").val();
        var score = parseFloat($("#score").val());
        var unitCount = parseInt($("#unitCount").val());

        if (!score || !unitCount || score < 0 || score > 20 || unitCount < 0 || unitCount > 4) {
            alert("مقادیر ناصحیح");
            return;
        }
        $("#data").find(".resRow").remove();
        var row = $("<tr></tr>").addClass("row").append("<td class='n'>" + name + "</td>").append("<td class='s'>" + score + "</td>").append("<td class='uc'>" + unitCount + "</td>");
        $("#data").append(row);
        $("#btnCal").click();
    });
    
    function getAvg() {
    var res = 0;
    var rows = $(".row");
    var totalUnits = 0;
    rows.each(function () {
        var score = parseFloat($(this).find(".s").text()) || 0;
        var unitCount = parseFloat($(this).find(".uc").text()) || 0;
        totalUnits += unitCount;
        res += score * unitCount;
    });
    return (res / totalUnits).toFixed(2);
}

//-------------------------------------------------
function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual...