javascript - 使用 jquery 进行时间跟踪

标签 javascript jquery

到目前为止,我拥有的是一个表格,用户可以在其中输入他们的小时、分钟、事件名称以及该事件的类别。用户可以根据需要添加/删除行。

我需要完成的是,当用户单击“计算”按钮时,它将添加小时/分钟,然后将输入值存储在“事件”和“类别”中。

这是我迄今为止所拥有的 fiddle 。 http://jsfiddle.net/os214gru/

<!DOCTYPE html><html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>English Styles Test</title>

        <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.17.2/build/cssreset/cssreset-min.css">
        <link href="http://explore.hawkeslearning.com/portal/content/css/learn_content_styles.css" rel="stylesheet">
        <link href="css/form-styles.css" rel="stylesheet">



        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

    <script type="text/javascript">
    // if Google is down, it looks to local file...
    if (typeof jQuery == 'undefined') {
      document.write(unescape("%3Cscript src='js/jquery-1.11.2.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
    </script>
    <script type="text/javascript" src="js/clone-form-td.js"></script>

</head>
<body>
<!-- https://jqueryui.com/dialog/ 
http://www.jacklmoore.com/notes/jquery-modal-tutorial/ -->
<div id="screenContainer">
    <div id="screenContainerEng">

    <div class='budgetForm-ENG'>
        <form action="#" method="post" id="BudgetFormEng">
            <table>
                <thead>
                    <tr>
                        <th colspan='4'>Time Budget Calculator</th>
                    </tr>
                    <tr>
                        <th id='hourLabel'>Hour</th>
                        <th id='minuteLabel'>Minutes</th>
                        <th id='activityLabel'>Activity</th>
                        <th id='categoryLabel'>Category</th>
                    </tr>
                </thead>
                <tbody>
                    <tr id="CloneRow">
                        <td>
                            <input class="input_hr" type="number" value="0" name="ID_hour" id="ID_hour" aria-labeledby="hourLabel" min="0">
                        </td>
                        <td>
                            <input class="input_min" type="number" value="0" name="ID_min" id="ID_min" min="0" max="59" aria-labeledby="minuteLabel">
                        </td>
                        <td>
                            <input type="text" name="ID_act" id="ID_act" aria-labeledby="activityLabel">
                        </td>
                        <td>
                            <select class="input_cat" name="ID_cat" id="ID_cat" aria-labeledby="cateogryLabel">
                                <option value="" selected="selected" disabled="disbled">
                                    Select Category
                                </option>

                                <option value="Class">
                                    Class
                                </option>

                                <option value="Entertainment">
                                    Entertainment
                                </option>

                                <option value="Exercise">
                                    Exercise
                                </option>

                                <option value="Extracurricular">
                                    Extracurricular
                                </option>

                                <option value="Family">
                                    Family
                                </option>

                                <option value="Meal">
                                    Meal
                                </option>

                                <option value="Other">
                                    Other
                                </option>

                                <option value="Personal">
                                    Personal
                                </option>

                                <option value="Sleep">
                                    Sleep
                                </option>

                                <option value="Social">
                                    Social
                                </option>

                                <option value="Study">
                                    Study
                                </option>

                                <option value="Work">
                                    Work
                                </option>
                            </select>
                        </td>
                    </tr>
                    <tr id="CloneRow0">
                        <td>
                            <input class="input_hr" type="number" value="0" name="ID0_hour" id="ID0_hour" aria-labeledby="hourLabel" min="0">
                        </td>
                        <td>
                            <input class="input_min" type="number" value="0" name="ID0_min" id="ID0_min" min="0" max="59" aria-labeledby="minuteLabel">
                        </td>
                        <td>
                            <input type="text" name="ID0_act" id="ID0_act" aria-labeledby="activityLabel">
                        </td>
                        <td>
                            <select class="input_cat" name="ID0_cat" id="ID0_cat" aria-labeledby="cateogryLabel">
                                <option value="" selected="selected" disabled="disbled">
                                    Select Category
                                </option>

                                <option value="Class">
                                    Class
                                </option>

                                <option value="Entertainment">
                                    Entertainment
                                </option>

                                <option value="Exercise">
                                    Exercise
                                </option>

                                <option value="Extracurricular">
                                    Extracurricular
                                </option>

                                <option value="Family">
                                    Family
                                </option>

                                <option value="Meal">
                                    Meal
                                </option>

                                <option value="Other">
                                    Other
                                </option>

                                <option value="Personal">
                                    Personal
                                </option>

                                <option value="Sleep">
                                    Sleep
                                </option>

                                <option value="Social">
                                    Social
                                </option>

                                <option value="Study">
                                    Study
                                </option>

                                <option value="Work">
                                    Work
                                </option>
                            </select>
                        </td>
                    </tr>
                    <tr id="CloneRow1" class='clonedInput'>
                        <td>
                            <input class="input_hr" type="number" value="0" name="ID1_hour" id="ID1_hour" aria-labeledby="hourLabel" min="0">
                        </td>
                        <td>
                            <input class="input_min" type="number" value="0" name="ID1_min" id="ID1_min" min="0" max="59" aria-labeledby="minuteLabel">
                        </td>
                        <td>
                            <input class="input_act" type="text" name="ID1_act" id="ID1_act" aria-labeledby="activityLabel">
                        </td>
                        <td>
                            <select class="input_cat" name="ID1_cat" id="ID1_cat" aria-labeledby="cateogryLabel">
                                <option value="" selected="selected" disabled="disbled">
                                    Select Category
                                </option>

                                <option value="Class">
                                    Class
                                </option>

                                <option value="Entertainment">
                                    Entertainment
                                </option>

                                <option value="Exercise">
                                    Exercise
                                </option>

                                <option value="Extracurricular">
                                    Extracurricular
                                </option>

                                <option value="Family">
                                    Family
                                </option>

                                <option value="Meal">
                                    Meal
                                </option>

                                <option value="Other">
                                    Other
                                </option>

                                <option value="Personal">
                                    Personal
                                </option>

                                <option value="Sleep">
                                    Sleep
                                </option>

                                <option value="Social">
                                    Social
                                </option>

                                <option value="Study">
                                    Study
                                </option>

                                <option value="Work">
                                    Work
                                </option>
                            </select>
                        </td>
                    </tr>
                    <tr class='output'>
                        <th>Total:</th>
                        <td id='output' colspan='3'></td>
                    </tr>
                </tbody>
            </table>

            <div id="addDelButtons">
               <input type="button" id="btnAdd" value="add section" class='fontawesome-plus' aria-label="Add Row"> 
                <input type="button" id="btnDel" value="remove section above" class='fontawesome-minus' aria-label="Remove Last Row">
                <input type="button" id="btnRes" value="Reset form" aria-label="Reset Form">
                <input type="button" id="btnCalc" value="Calculate" aria-label="Reset Form">
            </div>
        </form>
    </div>

    <p id='demo'></p>

    </div>
</div>

</body>
</html>

这是JS

$(function () {
    $('#btnAdd').click(function () {
        var num     = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
            newNum  = new Number(num + 1),      // The numeric ID of the new input field being added, increasing by 1 each time
            newElem = $('#CloneRow' + num).clone().attr({'id': 'CloneRow' + newNum}).addClass('addedRow').fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value

    /*  This is where we manipulate the name/id values of the input inside the new, cloned element
        Below are examples of what forms elements you can clone, but not the only ones.
        There are 2 basic structures below: one for an H2, and one for form elements.
        To make more, you can copy the one for form elements and simply update the classes for its label and input.
        Keep in mind that the .val() method is what clears the element when it gets cloned. Radio and checkboxes need .val([]) instead of .val('').
    */
        // Title - select
        newElem.find('.input_hr').attr('id', 'ID' + newNum + '_hour').attr('name', 'ID' + newNum + '_hour').val('0');

        // First name - text
        newElem.find('.input_min').attr('id', 'ID' + newNum + '_min').attr('name', 'ID' + newNum + '_min').val('0');

        // Last name - text
        newElem.find('.input_act').attr('id', 'ID' + newNum + '_act').attr('name', 'ID' + newNum + '_act').val('');

        // Color - checkbox
        newElem.find('.input_cat').attr('id', 'ID' + newNum + '_cat').attr('name', 'ID' + newNum + '_cat').val('');

    // Insert the new element after the last "duplicatable" input field
        $('#CloneRow' + num).after(newElem);
        $('#ID' + newNum + '_title').focus();

    // Enable the "remove" button. This only shows once you have a duplicated section.
        $('#btnDel').attr('disabled', false);

    // Right now you can only add 13 sections, for a total of 15. Change '13' below to the max number of sections you want to allow.
        if (newNum == 13)
        $('#btnAdd').attr('disabled', true).prop('value', "That's all, folks!"); // value here updates the text in the 'add' button when the limit is reached 
    });

    $('#btnDel').click(function () {
    // Confirmation dialog box. Works on all desktop browsers and iPhone.
        if (confirm("Are you sure you wish to remove this section? This cannot be undone."))
            {
                var num = $('.clonedInput').length;
                // how many "duplicatable" input fields we currently have
                $('#CloneRow' + num).slideUp('slow', function () {$(this).remove();
                // if only one element remains, disable the "remove" button
                    if (num -1 === 1)
                $('#btnDel').attr('disabled', true);
                // enable the "add" button
                $('#btnAdd').attr('disabled', false).prop('value', "add section");});
            }
        return false; // Removes the last section you added
    });
    // Enable the "add" button
    $('#btnAdd').attr('disabled', false);
    // Disable the "remove" button
    $('#btnDel').attr('disabled', true);
    // Reset the entire form
    $('#btnRes').click( function () {
    {
    // Confirmation dialog box. Works on all desktop browsers and iPhone.
        if (confirm("Do you really want to reset the form? All data will be lost."))
            {
                 document.getElementById("BudgetFormEng").reset();
                 $('.addedRow').remove();
                 $('#output').empty();
             };
        return false;
    };});

    $('#btnCalc').click(function() {
        var hours = $(".input_hr").serializeArray();
        var minutes = $(".input_min").serializeArray();
        var categories = $(".input_cat").serializeArray();
        var blargh  = [];
        for(var i=0;i<categories.length;i++){
           blargh.push({cat:categories[i].value,hour:hours[i].value,minute:minutes[i].value});//add object literal
        }

       /* jQuery.each(blargh, function (i, cat) {
            console.log(i.value)
        });

       /* var totalHours = 0;
        var totalMins = 0;

        jQuery.each(hours, function( i, hours) {
            totalHours += parseInt(hours.value) * 60
        });

        jQuery.each(minutes, function( i, minutes) {
            totalMins += parseInt(minutes.value) 
        });

        var totalTime = totalHours + totalMins;
        var realMin = totalTime % 60;
        var realHour = Math.floor(totalTime / 60);

        $('#output').empty();
        $('#output').append(realHour + ' hours, ' + realMin + ' minutes');*/

    })
});

最佳答案

首先:如果您对元素使用类而不是 id,您将节省大量时间和工作。

仅当您为 TR 指定一个 trclass 类、您的 Activity 指定为“input_act”类并且类别指定为“input_cat”类时,此解决方案才有效

我仅在控制台上输出类别和事件,您自己决定如何处理它。

实际计算相当简单:

$(function() {
      $("#btnCalc").click(function(e) {
        e.preventDefault();
        calcIt();
      });
}

function calcIt() {
var hours = 0;
var minutes = 0;
var activities = "";
var cats = "";
  $(".trclass").each(function(index) {
  hours += parseInt($(this).children("td").children(".input_hr").val()); 
  minutes += parseInt($(this).children("td").children(".input_min").val());   
  activities += $(this).children("td").children(".input_act").val();   
  cats += $(this).children("td").children(".input_cat").val();   
  });
$("#output").html(hours+":"+minutes);
console.log(activities);
console.log(cats);
}

DEMO

关于javascript - 使用 jquery 进行时间跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389051/

相关文章:

javascript - 如何防止 PHP 游戏从 AJAX 调用中重新实例化

javascript - 根据鼠标位置添加 Css 类

javascript - 需要额外的功能标签吗?

javascript - 动态添加 div 作为 droppable、ng-repeat 和 Jquery

javascript - 通过 jQuery 根据其深度删除 HTML 元素

javascript - 如何将值从一个区域转移到另一个区域

javascript - react 大括号问题

JavaScript 压缩

javascript - 如何使用jquery显示具有许多不同div的所有数据的每2项?

javascript - 按钮背景颜色不起作用