John Davidson

javascript - how to submit timer value in a form when click stop?

0 comments
Message:


how can i make this timer to submit form name as in name="time" and send value to $_POST['time'] when someone clicks stop and then the value i can store it into mysql database?


    <div id="timer"></div>
<button type="button" onclick="stopTimer()">Stop</button>

<?php
$time = strtotime('01:00:00');
?>


<script>
var startTime = <?php echo $time;?>;
//var startTime = Date.now();
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var container = document.getElementById('timer');

function stopTimer() {
clearInterval(timer);
}

function pad(n){
return ('00' + n).slice(-2);
}

var timer = setInterval(function(){
var currentTime = Date.now();
var difference = currentTime - startTime;

var hours = pad((difference / hour) | 0);
var minutes = pad(((difference % hour) / minute) | 0);
var seconds = pad(((difference % minute) / second) | 0);

container.innerHTML = hours + ':' + minutes + ':' + seconds;

// This only represents time between renders. Actual time rendered is based
// on the elapsed time calculated above.
}, 250);
</script>

thanks for your help



My Answer:
You can achieve this by creating a form with an input field for the timer value and a hidden input field for the form name. Then, you can use JavaScript to update the hidden input field with the form name when the stop button is clicked.

Here's an example code snippet to demonstrate this:

HTML:
html








JavaScript:
javascript
let timer;
let startTime;
const timerValue = document.getElementById('timerValue');
const formName = document.getElementById('formName');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');

startButton.addEventListener('click', function() {
startTime = Date.now();
timer = setInterval(updateTimer, 1000);
});

stopButton.addEventListener('click', function() {
clearInterval(timer);
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
timerValue.value = elapsedTime;
formName.value = 'Your Form Name'; // Update this with your form name
document.getElementById('timerForm').submit();
});

function updateTimer() {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
timerValue.value = elapsedTime;
}


In this code snippet, when the stop button is clicked, the form will be submitted with the timer value and the form name. You can update the `formName.value` with your desired form name.

Rate this post

3 of 5 based on 9264 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us