km1882
km1882

Reputation: 750

Javascript for displaying day based on the date

I have the following set of tags:

<input type="text" class="form" id="reserveDate" placeholder="Select date"
       onclick="showHours(reserveDate);" onfocus="(this.type='date')" required>
<p id="demo"></p>  

My JS code is the following:

function showHours(reserveDate) {
    var d = reserveDate.getDay();
    if( d >= 0){
        document.getElementById("demo").innerHTML = "sunday";
    }
}  

I am trying to debug using CDT and I am getting the following error message after var d = reserveDate.getDay();:

Uncaught TypeError: undefined is not a function.

Is there a reason why I can not use getDay() here?

Upvotes: 0

Views: 726

Answers (3)

tmarwen
tmarwen

Reputation: 16354

Since you are trying to call the getDate() method inside your showHours() function, you should pass in a date object (instantiated from the value of you current text input), so that the callback for the click event look like the follwing: showHours(new Date(this.value));

<input 
  type="text" 
  class="form" 
  id="reserveDate" 
  placeholder="Select date" 
  onClick="showHours(new Date(this.value))" 
  onfocus="(this.type='date')" 
  required />

<p id="demo"></p>

Then keep your JS function as it is:

function showHours(reserveDate) {
  var d = reserveDate.getDay();
  if( d >= 0){
    document.getElementById("demo").innerHTML = "sunday";
  }
}

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You're passing the inputs ID to the showHours function, and as all ID's are stored as window.ID in the global scope you're getting the HTML element, not a date object.

Remove the inline onclick handler and use proper event handlers instead

<input type="date" class="form" id="reserveDate" placeholder="Select date" required>

and then do

var elem = document.getElementById('reserveDate');

elem.addEventListener('change', function() {
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var date = new Date(this.value);
    var day  = date.getDay();

    document.getElementById('demo').innerHTML = days[day];
}, false);

FIDDLE

Upvotes: 1

Kostar
Kostar

Reputation: 47

Your implementation of .getDay() is probably wrong or you're passing in a wrong type of variable as reserveDate. Latter is more likely. Check with console.log(reserveDate) to see what the variable actually is and make sure its a type of Date object.

Upvotes: 0

Related Questions