1

I'm trying to change the color of the input text whenever the$visa_expired is the same date as today. But right now, I get an error saying Invalid Date

Here is my code:

  <script type="text/javascript">


function checkFilled() {

  var today = new Date();
  var expired = new Date("<?php echo $visa_expiry; ?> ");
  var inputVal = document.getElementById("expiry");

    if (inputVal.value == "") {
        inputVal.style.backgroundColor = "red";
        window.alert(today);
    }
    else{
        inputVal.style.backgroundColor = "yellow";
    }
}

checkFilled();

  </script>

Here is my HTML:

<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
Kappa
  • 1,015
  • 1
  • 16
  • 31

3 Answers3

2

This is similar to what I have done in the past

var inputElement = document.getElementById("expiry");
var inputDate = inputElement.value;
var expired = new Date();
var today = new Date();

expired.setUTCFullYear(inputDate.split("/")[2], inputDate.split("/")[0] - 1, inputDate.split("/")[1]);


if(today === expired) {
    inputElement.style.backgroundColor = "red";
    window.alert(today);
} else {
    inputElement.style.backgroundColor = "yellow";
}

Also it looks like you need to change

<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">

To

<input type="text" class="form-control" size="5" value="<?php echo $visa_expiry; ?>" id="expiry">

Just note that since you are using a input form box, its always possible that someone would enter something like 10-12-2016 instead of the 10/12/2016 format you may be expecting. Which would cause the above code to fail. You might want to consider finding a datepicker, or at the least change the <input type="text"> to <input type="date">

Then create some code to format the date to what you want.

References

Community
  • 1
  • 1
0

If 10/13/2016 is the value of $visa_expiry it should not give error. check this link and run the fiddle it alert date. http://phpfiddle.org/main/code/hpia-ub40

<script type="text/javascript">


function checkFilled() {

  var today = new Date();
  var expired = new Date("<?php echo $visa_expiry; ?> ");
  var inputVal = document.getElementById("expiry");

    if (today >= expired) {
        inputVal.style.backgroundColor = "red";
    }
    else{
        inputVal.style.backgroundColor = "yellow";
    }
}

checkFilled();

  </script>
aasiph
  • 237
  • 2
  • 7
-1

You are trying to display an Date Object in alert, which expects a string input. You should use getDate() instead.

try this:

var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();

today = day + '/' + month + '/' + year
J. Mathew
  • 29
  • 4