3

Right now I have a project that calculates startTime, EndTime - breakTime. and displays that into a WorkedHours Field.

Like this: enter image description here

I have a time picker to choose the time, but my calculate script dosen't run after I changed the value. It runs when I step into the text box. So if I were to change it like this: enter image description here

It will not updated Tid Jobbad Until I step into that same textbox again. How do I make it call the function each time the value changes?

This is the script:

    $(function() {
    $('#breakTime,#startTime,#endTime')
      .blur(CalculateTime);
    CalculateTime();
});


function CalculateTime() {
    try {
        var originalStartTime = $('#startTime').val(),
          originalEndTime = $('#endTime').val(),
          originalBreakTime = $('#breakTime').val();

        // breaking hours and minutes. needed format: HH:mm
        var startHours = originalStartTime.substring(0, 2).replace(':', ''),
          startMinutes = originalStartTime.substring(3, 5),
          endHours = originalEndTime.substring(0, 2).replace(':', ''),
          endMinutes = originalEndTime.substring(3, 5);

        // momentJs variables
        var mStart = moment().hour(startHours).minute(startMinutes),
          mEnd = moment().hour(endHours).minute(endMinutes),
          mBreak = moment.duration(originalBreakTime);

        var result = mEnd.subtract(mStart).subtract(mBreak).format('HH:mm');

        $('#workedHours').val(result);

    } catch (err) {
        $('#workedHours').val(err);
    }
}
3
  • 1
    can you share a fiddle ? Commented Sep 10, 2015 at 10:18
  • Any relation? stackoverflow.com/questions/32498475/… Commented Sep 10, 2015 at 10:20
  • If you want to check if an input value has changed, you can use change event Commented Sep 10, 2015 at 10:20

1 Answer 1

1

Y're using blur event and it is sent to an element when it loses focus. So if you want to recalculate values on change, you need to bind onChange javascript event:

$('#breakTime, #startTime, #endTime').change(CalculateTime);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.