Reputation: 53
I have written a script like this
function calculateDiff(){
_start = "1:00 PM";
_end = "1:00 AM";
_start_time = parseAMDate(_start);
_end_time = parseAMDate(_end);
if (_end_time < _start_time){
_end_time = parseAMDate(_end,1);
}
var difference= _end_time - _start_time;
var hours = Math.floor(difference / 36e5),
minutes = Math.floor(difference % 36e5 / 60000);
if (parseInt(hours) >= 0 ){
if (minutes == 0){
minutes = "00";
}
alert(hours+":"+minutes);
}
}
function parseAMDate(input, next_day) {
var dateReg = /(\d{1,2}):(\d{2})\s*(AM|PM)/;
var hour, minute, result = dateReg.exec(input);
if (result) {
hour = +result[1];
minute = +result[2];
if (result[3] === 'PM' && hour !== 12) {
hour += 12;
}
}
if (!next_day) {
return new Date(1970, 01, 01, hour, minute).getTime();
}else{
return new Date(197var start = document.getElementById("usr1").value;
var end = document.getElementById("usr2").value;0, 01, 02, hour, minute).getTime();
}
}
here ,for _start and _end ,i have given values now i want these values should get from a textbox for that i have written code like
<form action="calculateDiff()">
Select start time:<input type="time" name="usr1">
Select end time: <input type="time" name="usr2">
<input type="submit">
</form>
when i select time in text box(usr1),how to get the time to the script function? plz help me
Upvotes: 2
Views: 67
Reputation: 1150
you can get value of input like this
var _start = document.getElementsByName("usr1")[0].value;
var _end = document.getElementsByName("usr2")[0].value;
Upvotes: 0
Reputation: 2791
Try this
_start = document.getElementsByName('usr1')[0].value; //It will fetch the value of the first element in the DOM with the name usr1
_end = document.getElementsByName('usr2')[0].value; //It will fetch the value of the first element in the DOM with the name usr2
Upvotes: 0
Reputation: 1298
I would suggest to add an id
property to the input fields:
<form action="calculateDiff()">
Select start time:<input type="time" name="usr1" id="startTime">
Select end time: <input type="time" name="usr2" id="endTime">
<input type="submit">
</form>
Now we can use document.getElementById
to get direct access to the html element:
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
document.getElementById("usr1")
will return the HTML textfield object itself and it has a few properties. One of them is value
which represents the content inside the textfield (you can even change it using javascript).
Read more about the input element here:
Upvotes: 1