I got problem when want to automatically click submit form with javascript, So in this case i want to submit the button Validate Answer when the time is up, is there something wrong with my code
here is the code that i call submit button
document.getElementById('onResult').submit();
and below is the full code
<script type="text/javascript">
var upgradeTime = #Model.Duration;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
//alert("Your Test Time Has Expire...!");]
document.getElementById('onResult').submit();
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
<span id="countdown" class="timer"></span>
#using (Html.BeginForm("CollectQuiz", "Exam"))
{
#Html.HiddenFor(model => #Model.Id, new { htmlAttributes = new { #class = "form-control" } })
for (var i = 0; i < Model.Soals.Count(); i++)
{
<div class="modal-content">
<div class="modal-body">
<p>#Model.Soals[i].Id #Model.Soals[i].Question</p>
#Html.HiddenFor(model => #Model.Soals[i].Id, new { htmlAttributes = new { #class = "form-control" } })
#for (var j = 0; j < Model.Soals[i].Choices.Count(); j++)
{
<p>
#Html.RadioButtonFor(m => m.Soals[i].SelectedAnswerId, Model.Soals[i].Choices[j].Id, new { id = "Question" + i.ToString() + "Answer" + j.ToString() })
<label for="Question#(i)Answer#(j)">#Model.Soals[i].Choices[j].Id #Model.Soals[i].Choices[j].Name</label>
</p>
}
<button class="btn btn-sm text-info"><b>Kesulitan: #Model.Soals[i].Difficulty</b> </button>
</div>
</div>
}
<input id="onResult" type="submit" value="Validate Answers" />
}
i got error
Document.getElementById(...).submit is not a function
submit is a method of form elements, not form control elements - clicking a submit button simply submits the form the button belongs to.
A simple way to invoke the submit button's action from the button is to use its form property to access its form and them submit the form:
document.getElementById('onResult').form.submit();
Alternatively you could obtain a reference to the form by other means and call its submit method.
I'm not familiar with whatever kind of frontend framework you are using here but I do know that submit needs to be done on a form element <form> rather than an <input>. I think if you change this to reference the form element ID you'll be good to go.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
Related
I have a simple form for readers to add comments. The comments entered are listed on the website when added. I would like to register the date the comment was entered and list that underneath the comment itself, as shown on the website. Can someone assist me with the JS code for this?
Thanks, Paul
const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');
// array to store the comments
var comments_arr = [];
if(!localStorage.commentData){localStorage.commentData = [];}
else{
comments_arr = JSON.parse(localStorage.commentData);
}
// to generate html list based on comments array
const display_comments = () => {
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length > 0){ // if there is content
// add the comment to the array
comments_arr.unshift(content);
localStorage.commentData = JSON.stringify(comments_arr);
// re-genrate the comment html list
display_comments();
// reset the textArea content
field.value = '';
}
}
window.addEventListener('load', display_comments);
<link href="comment.css" rel="stylesheet">
<form>
<textarea id="comment" placeholder="Your response pls." value=""></textarea>
</form>
<input id="submit" type="submit" value="add">
<h4>Responses</h4>
<div id="comment-box"></div>
<script src="comment.js"></script>
if you only want date stamp then remove the var current_time from the display_comments() function.
const display_comments = () => {
var date = new Date();
var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
var current_time = date.getHours()+":"+date.getMinutes()+":"+ date.getSeconds();
var date_time = current_date+" "+current_time;
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment} created at : ${date_time}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
let textbox=document.getElementById("textbox")
let comments=document.getElementById("comments")
let add=()=>{
let value=textbox.value
let ul=document.getElementById("ul")
let list=document.createElement("li")
var date = new Date();
var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var date_time = current_date+" "+strTime;
list.innerHTML=`comment:${value}`+" "+`Created At:${date_time}`
ul.insertBefore(list,ul.firstElementChild)
textbox.value=""
}
<textarea id="textbox" placeholder="Your response pls." value=""></textarea>
<button id="btn" onclick="add()">Add</button>
<div id="comments">
<h4>Responses</h4>
<ul id="ul"></ul>
</div>
I have my DOM like this :
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
And my JavaScript Like this :
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - currentTime
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
now I want to display value in my web page But it doesn't updating. seems like its freezes. but my "setInterval()" running properly.
How can I resolve this issue? need help!
You need instead of this code
let output = value - currentTime
use this
let output = value - (currentTime * 1000)
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - (currentTime * 1000)
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
Based on #Oleg Barabanov's answer I found one bug. If you didn't enter any value in text box or first added value then click on "Reset" and click on "Go" button then counter started with negative value. I fixed that issue with this code.
Script
var intervalClear;
var input = document.querySelector('#input');
var mint = document.querySelector('#mint');
var sec = document.querySelector('#sec');
var go_button = document.querySelector('#button');
var reset_button = document.querySelector('#reset');
go_button?.addEventListener('click', () => {
if (input.value != '' && input.value != 0 && parseInt(input.value) != NaN) {
startTimer(input.value, mint, sec);
}
});
reset_button?.addEventListener('click', () => {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
});
function startTimer(duration, minElement, secElement) {
clearInterval(intervalClear);
var timer = duration * 60, minutes, seconds;
intervalClear = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
minElement.textContent = minutes;
secElement.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (minutes == 0 && seconds == 0) {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
}
}, 1000);
}
DOM
<input type="number" id="input" placeholder="Enter time in minutes" >
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint">00</div>
<div class="sec" id="sec">00</div>
</div>
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
As #brombeer suggested, just create a form like this:
<form action="yoururl" method="post">
<input id="timer" type="number" disabled name="time" value="<?=$time?>" /> <!--here the value is shown-->
<button type="submit">Stop</button> <!--when you click here time=xx:xx:xx is sent to yoururl-->
</form>
You can then access it from JavaScript as timer and edit it ad shown in your question
I've been trying to add a simple stopwatch to my Rails app, and I've adapted the one I found here: https://jsfiddle.net/waqasumer/agru2bdL/
The code seems to work in the console (the timer starts and stops), but I'm getting this error when using the controls and the UI is not showing the stopwatch (it's just reading zero):
Uncaught TypeError: Cannot set property 'innerHTML' of null
Any help to get this working would be appreciated. I've included my code below.
var min = 0;
var sec = 0;
var msec = 0;
var getMin = document.getElementById("min");
var getSec = document.getElementById("sec");
var getmsec = document.getElementById("msec");
var interval;
function timer() {
msec++
getmsec.innerHTML = msec;
if (msec >= 100) {
sec++;
if (sec <= 9) {
getSec.innerHTML = "0" + sec;
} else {
getSec.innerHTML = sec;
}
msec = 0;
} else if (sec >= 60) {
min++;
if (min <= 9) {
getMin.innerHTML = "0" + min;
} else {
getMin.innerHTML = min;
}
sec = 0;
}
}
function start() {
interval = setInterval(timer, 10);
var btn = document.getElementById("start");
btn.disabled = true;
}
function stop() {
clearInterval(interval);
var btn = document.getElementById("start");
btn.disabled = false;
}
function reset() {
min = "00";
sec = "00";
msec = "00";
getMin.innerHTML = min;
getSec.innerHTML = sec;
getmsec.innerHTML = msec;
clearInterval(interval);
}
function lapTimer() {
var Laps = document.getElementById('laps');
Laps.innerHTML += "<div>" + " " + getMin.innerHTML + ":" + getSec.innerHTML + ":" + getmsec.innerHTML + "</div>";
}
<h1 class="title">Stopwatch</h1>
<div class="stopwatch">
<div class="circle">
<div class="time"><span id="min">00</span>:<span id="sec">00</span>:<span id="msec">00</span></div>
</div>
<div class="controls">
<button id="start" onclick="start()" type="button"><img class="controls-img" id="playButton" src="<%= asset_path( 'play_button.png' ) %>" /></button>
<button onclick="stop()" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'pause_button.png' ) %>" /></button>
<button onclick="lapTimer()" id="lapButton" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'lap.png' ) %>" /></button>
<button onclick="reset()" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'reset_button.png' ) %>" />
</button>
</div>
</div>
<br>
<div class="row" id="laps"></div>
The js code will executed, before the page is ready. You have 2 solutions. Put your js code at the end of the page or look here $(document).ready equivalent without jQuery
<--THIS IS THE TIMER I WANT --> UPDATED
Trying to get the timer to automatically hit the submit button and go to next page. There is a controller that scores the quiz so I need to use the #using htmlBeginForm used below. TIMER
<div class="row">
<div class="col-md-offset-1">
<section id="questionForm">
<h2>Questions</h2>
<form name="counter">
<input type="text" size="8"
name="d2">
</form>
<script type="text/javascript">
var minutes = 1
var seconds = 00
document.counter.d2.value = '30:00'
function display()
{
if (seconds <= 0)
{
minutes -= 1
seconds += 59
}
if (minutes <= -1)
{
function nextQuestion() {
$("#questionform").trigger("submit");
}
$(document).ready(function () {
setTimeout(function () { nextQuestion() }, 5000);
});
}
else
seconds -= 1
document.counter.d2.value = minutes + ":" + seconds
setTimeout("display()", 1000)
}
display()
</script>
#using (Html.BeginForm("Index", "Questions", FormMethod.Post, new { #id = "questionform" }))
{
#Html.EditorFor(x => x.Questions)
<input type="submit" id="submit" class="btn btn-default" value="Submit" />
}
</section>
</div>
It seems you are trying to submit the form after a given time. For this you can use just the setTimeout function.
#using htmlBeginForm is the Razor syntax for creating form tag and at the end you will have the same old form tag in your rendered View. You can use below code to give your own ID.
#using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { #id = "questionform" }))
Since you have added jQuery tag, I assume you can use jQuery and try following JavaScript code.
I assume your layout page has jQuery and script section as below.
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
</html>
Then your view should be like below.
<div class="col-md-offset-1">
<section id="questionForm">
<h2>Questions</h2>
<div id='countdown'></div>
#using (Html.BeginForm("Index", "Questions", FormMethod.Post, new { #id = "questionform" }))
{
#Html.EditorFor(x => x.Questions)
<input type="submit" id="submit" class="btn btn-default" value="Submit" />
}
</section>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function() {
countdown('countdown');
});
function countdown(element) {
var interval;
var minutes = 1;
var seconds = 30;
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
el.innerHTML = "Time's Up!";
clearInterval(interval);
$("#questionform").trigger("submit");
return;
} else {
minutes--;
seconds = 60;
}
}
el.innerHTML = minutes + ' : ' + seconds;
seconds--;
}, 1000);
}
</script>
}
JSFiddle Example