Kody R.
Kody R.

Reputation: 2460

Alerting input time returning incorrectly

I'm trying to input a time and have it returned back to me so I can alert it. I get two errors: 1) "time.split is not a function"(which I guess is because I'm not passing a string 2) when I try to add .toString() to either the argument or to time.toString().split(/:/) it doesn't get returned correctly. How would I get it to alert the time? Thanks!

function changeTime(time) {
    time = time.split(/:/);

    if (time[0] < 12) {
        return (time[0] + time[1] + " AM"); 
    } else if (time[0] == 12) {
        return (time[0] + time[1] + " PM");
    } else if(time[0] > 12) {
        return ((time[0] - 12) + time[1] + " PM");
    } else {
        return("Please enter a valid time!");
    }
}

getTime.addEventListener('click', function() {
    alert("The time is " + changeTime(timeText));
});

EDIT: here are my input fields for "timeText" and "getTime"

   <button id="getTime">Get Time</button>
   <input type="time" id="timeText" />

Upvotes: 0

Views: 29

Answers (1)

Richard Hamilton
Richard Hamilton

Reputation: 26444

It seems like timeText is an input field. In that case, to get the string, you have to call the value property.

I also wanted to make a couple improvements to your function

  1. Your time was showing something like this 400PM. I improved it so it now shows 4:00PM.
  2. I also made a check to see if the time field had a value. Only if it did, would I alert the time. Previously it showed The time is undefined pm

var getTime = document.getElementById("get-time");
var timeText = document.getElementById("time-text");

function changeTime(time) {
    time = time.split(/:/);

    if (time[0] < 12) {
        return (time[0] + ":" + time[1] + " AM"); 
    } else if (time[0] == 12) {
        return (time[0] + ":" + time[1] + " PM");
    } else if(time[0] > 12) {
        return ((time[0] - 12) + ":" + time[1] + " PM");
    } else {
        return("Please enter a valid time!");
    }
}

getTime.addEventListener('click', function() {
  if (timeText.value) { 
      alert("The time is " + changeTime(timeText.value));
  }
});
<input id="time-text" type="time">

<button id="get-time">Get Time</button>

Upvotes: 1

Related Questions