Reputation: 2460
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
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
400PM
. I improved it so it now shows 4:00PM
.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