0

I am a total begginer at JavaScript and this question probably shows that.

I have this code:

<script>
    function treatAsUTC(s) {
        var b = s.split(/\D/);
        return new Date(Date.UTC(b[2], b[1]-1, b[0]));
    }

    function daysBetween(startDate, endDate) {
        startDate = treatAsUTC(startDate);
        endDate = treatAsUTC(endDate);
        return (endDate - startDate) / 8.64e7;
    }

    function calcDiff() {
        document.querySelector('#tdays').value = 
           (daysBetween(document.querySelector('#startPicker').value,
            document.querySelector('#endPicker').value));
    }
</script>

<input type="text" id="sod" class="startd" value="10/02/2016" />d/m/y
<input type="text" id="dos" class="endd"  value="12/02/2016" />d/m/y
<br>
<button onclick="calcDiff()">Calculate difference in days</button>
<input type="text" id="tdays" readonly>Days

Now I want the result to permanatly be displayed and updated as the dates change (they will be date pickers) rather than onClick.

I have tried innerHTML and document.write but I cant get it to work.

Any help will be greatly appreciated.

Thansk in advnace.

Ian

4
  • 1
    Where's #tdays? You mean #result? Commented Feb 9, 2016 at 15:27
  • You can add onkeyup event on date input. Commented Feb 9, 2016 at 15:28
  • @artm yeah sorry, results stay the same Commented Feb 9, 2016 at 15:32
  • Are you trying to add the difference in days, and where do you want to output it Commented Feb 9, 2016 at 15:36

4 Answers 4

3

Basically you are using wrong selectors in most of the places.

#sod means element with id sod. The same apply for the others as well.

Added this document.querySelector('#sod').addEventListener('input', calcDiff); to call function when you change the input values.

function treatAsUTC(s) {
  var b = s.split(/\D/);
  return new Date(Date.UTC(b[2], b[1] - 1, b[0]));
}

function daysBetween(startDate, endDate) {
  startDate = treatAsUTC(startDate);
  endDate = treatAsUTC(endDate);
  return (endDate - startDate) / 8.64e7;
}

function calcDiff() {
  document.querySelector('#result').value =
    (daysBetween(document.querySelector('#sod').value,
      document.querySelector('#dos').value));
}
document.querySelector('#sod').addEventListener('input', calcDiff);
document.querySelector('#dos').addEventListener('input', calcDiff);
<input type="text" id="sod" class="startd" value="10/02/2016" />d/m/y
<input type="text" id="dos" class="endd" value="12/02/2016" />d/m/y
<br>
<button onclick="calcDiff()">Calculate difference in days</button>
<input type="text" id="result" readonly>Days

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, can this work without the need for the button? I need it to constantly display the days with any changes that may happen to the date.
@snookian I updated the code. This will now work everytime you make changes.
Hi, thanks for trying to help me. Really do appreciate it. The value doesnt update if the second date is changed, only the first . Also they value isnt displayed straight away, only when the firstdate is changed,
@snookian In that case just change the selector to querySelector('#sod')
0

Without the help of any frameworks, JavaScript needs something to tell it when to update so having the date inputs (sod & dos) fire off the calcDiff() function on change is probably your best bet.

<input onchange="calcDiff()"type="text" id="sod" class="startd" value="10/02/2016" /> 

This will fire when the value has change and focus is lost on the input.

Jcubic's suggestion of onkeyup will give the user more immediate feedback but you may want to add some error handling for when it fires but a valid date hasn't been entered.

2 Comments

Change event work only on blur, if you want to have live events you need to use onkeyup.
@jcubic - Yes, this is in my original answer. "and focus is lost ... Jcubic's suggestion of onkeyup will give the user more immediate feedback"
0

With what you have here, #tdays, #startPicker, and #endPicker are supposed to be elements that either contain a value or can have it set. They don't exist in your HTML and that's why it's failing.

I replaced them with #result, #sod, and #dos and that got it going.

Also, consider using developer tools in your browser. As soon as I created a jsFiddle and hit run, I was able to see the javascript error in the console and more times than not it really helps with stuff like this.

Comments

0

    $(document).ready(function() {
        $( "#startdate,#enddate" ).datepicker({
            changeMonth: true,
            changeYear: true,
            firstDay: 1,
            dateFormat: 'dd/mm/yy',
        })

        $( "#startdate" ).datepicker();
        $( "#enddate" ).datepicker();

        $('#startdate').change(function() {
            var start = $('#startdate').datepicker('getDate');
            var end   = $('#enddate').datepicker('getDate');

            if (end==null) {
              //do nothing
            } else if (end!=null && start<end) {
                var days   = (end - start)/1000/60/60/24;
                $('#days').val(days);
            } else {
                alert ("Wrong Choice");
                $('#startdate').val("");
                $('#enddate').val("");
                $('#days').val("");
            }
        }); //end change function
        $('#enddate').change(function() {
            var start = $('#startdate').datepicker('getDate');
            var end   = $('#enddate').datepicker('getDate');

            if (start==null) {
              //do nothing
            } else if (start!=null && start<end) {
                var days   = (end - start)/1000/60/60/24;
                $('#days').val(days);
            } else {
                alert ("Wrong Choice");
                $('#startdate').val("");
                $('#enddate').val("");
                $('#days').val("");
            }
        }); //end change function
    }); //end ready
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<input type="text"  placeholder="date1" id="startdate">
<input type="text" placeholder="date2" id="enddate">
<input type="text" id="days">

4 Comments

Why do you setting dateFormat to dd/mm/yy and then change it to dd-mm-yy, can't you just set it to dd-mm-yy in first call to datepicker? Also you need to add change event to #startdate too.
sorry didnt notice that i will edit the post now ... there is not need to have a change event on #startdate since i got the two date in #enddate change event and also validated them from the "alert("wrong choice")
If you change #startdate no code will be executed. You need to add $('#enddate,#startdate').change(...
i can say that you are right but that will also smash my validation but give a minute let me edit

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.