onclick submit can't call JavaScript function with setTimeout and document.getElementById - javascript

I am tring to call timedText() function when click on submit, and than call setTimeout() and replace tag <p> with 1 seconds, 2 seconds and 3 seconds.
<script>
function timedText()
{
var x=document.getElementById('txt1');
var t1 = setTimeout(function(){x.innerHTML="1 seconds"},1000);
var t2 = setTimeout(function(){x.innerHTML="2 seconds"},2000);
var t3 = setTimeout(function(){x.innerHTML="3 seconds"},3000);
}
</script>
<p>
<a href="#">
Izmeni<p id="txt1"></p>
</a>
</p>
<input type="submit" name="answer" value="Postavi" onclick="timedText()"/>

That is because the submit button is submitting the page.
Personally, I like to use <button onclick="dosomething()">Click me!</button>. But some browsers treat that as a submit button too... so make sure you return false; in the event handler (ie. onclick="dosomething(); return false;")

A few things changed:
Changed submit button to a standard button. Submit button probably reloading page, and never firing action. Either way, not appropriate for a function call onclick.
Changed onclick on the html button to be assigned by the javascript. It's the modern way to do this, and more reliable.
Cleaned up the html slightly. The p tag was inside the anchor, which isn't ideal. This is optional mostly though.
JSFiddle
http://jsfiddle.net/q9Juv/
HTML
<p>
Izmeni
<p id="txt1"></p>
</p>
<input type="button" id="button" name="answer" value="Postavi" />
JS
function timedText(){
var x=document.getElementById('txt1');
var t1=setTimeout(function(){x.innerHTML="1 seconds"},1000);
var t2=setTimeout(function(){x.innerHTML="2 seconds"},2000);
var t3=setTimeout(function(){x.innerHTML="3 seconds"},3000);
}
document.getElementById('button').addEventListener('click',timedText);

Perhaps this will help you to see things in a clearer way (hopefully):
<p>Izmeni<p id="txt1"></p></p>
<input type="submit" name="answer" value="Postavi" onclick="StartTimer(3)"/>
<script type="text/javascript">
var timerId = null;
var element = document.getElementById("txt1");
function StartTimer(numOfSeconds)
{
element.innerHTML = String(numOfSeconds)+" seconds";
timerId = setInterval(TimerIsr,1000);
}
function StopTimer()
{
clearInterval(timerId);
element.innerHTML = "";
}
function TimerIsr()
{
var numOfSeconds = Number(element.innerHTML.split(" ")[0]);
if (numOfSeconds > 2)
element.innerHTML = String(numOfSeconds-1)+" seconds";
else if (numOfSeconds == 2)
element.innerHTML = "1 second";
else
StopTimer();
}
</script>

Related

SetInterval does not run from HTML form's onClick event

I just wrote a timer function that does count down from 5 seconds on the page. Next I wanted to create a form that would call the timer function when submitted.
But even though the onClick triggers the function (and console logs "hi"), it never executes setInterval.
Is there a reason why setInterval works when I call the function immediately, but not when I submit the form? After some research, I still can't work out the reason for this.
<body>
<h1 id="title">
This a simple timer
<form action="">
<input type="text" name="duration" />
<input type="submit" onclick="timer()" />
</form>
</h1>
<script src="src/index.js"></script>
</body>
javascript
const title = document.getElementById("title");
const btn = document.getElementById("btn");
const timer = () => {
console.log("hi");
let interval = 5;
let countdown = window.setInterval(() => {
title.innerText = "00:" + interval;
interval--;
if (interval === 0) {
title.innerText = "DONE";
clearInterval(countdown);
}
}, 1000);
};
Since HTML forms with action attribute set to empty string submit their form to the current page, you are reloading your page every time you submit since why your JS function never gets called
what you can do is prevent default(reload) behavior by calling e.preventDefault() before your console.log("hi"); statement.
and your <input type="submit"... would change to <input type="submit" onclick="timer(event)" />
also don't forget to add the parameter to const timer = e => {...
Submitting a form in html means that the URL specified with action will be loaded with the data from you form. If you set action to an empty string, the current page is reloaded with the form's data. So in your case you are reloading your page everytime you click the submit button.
If you just want to start the timer with a button, you don't need a form and you don't need an input of type submit. Use
<body>
<h1 id="title">
This a simple timer
</h1>
<input type="text" name="duration" />
<input type="button" onclick="timer()" value="click me!" />
<script src="src/index.js"></script>
</body>
Also, you shouldn't put anything in your <h1> apart from the actual text of your title.
I see two problems here. Your html structure. You should try this instead. I added “event” so I could target the input element. But you could also give the form tag a name or set an I’d to target it directly when the submit button gets clicked.
<body>
<h1 id="title"> This a simple timer </h1>
<form action="">
<input type="text" name="duration" />
<input type="submit" onclick="timer(event)"/>
</form>
<script src="src/index.js"></script>
</body>
Previously when the onclick event triggers you update the DOM by replacing the text contents in #title and that tag wraps the form also. I think you should make them independent. And 2, the page gets reloaded so you should handle the page submission by using preventDefault(); on the form. see example below
const title = document.getElementById("title");
const btn = document.getElementById("btn");
const timer = e => {
e.preventDefault();
console.log("hi");
let interval = 5;
let countdown = window.setInterval(() => {
title.innerText = "00:" + interval;
interval--;
if (interval === 0) {
title.innerText = "DONE";
clearInterval(countdown);
}
}, 1000);
};
Here is another approach, i adjusted the html and javascript.
No onclick event
<h1 id="title"> This a simple timer </h1>
<form action="" name="simple_timer">
<input type="text" name="duration" />
<input type="submit"/>
</form>
We just set a form name.
Javascript set to listen for any submission by that form then prevents it from occuring.
const title = document.getElementById("title");
const timer = document.forms['simple_timer'];
timer.addEventListener('submit', (e) => {
e.preventDefault();
console.log("hi");
let interval = 5;
let countdown = window.setInterval(() => {
title.innerText = "00:" + interval;
interval--;
if (interval === 0) {
title.innerText = "DONE";
clearInterval(countdown);
}
}, 1000);
});
Guess that’s all.

Unable to get user input from input field and assign it to another div's innerHTML

I know that this question sounds silly but i am curious why i can avoid this problem in JavaScript. Now in the code below i have given :
var btn=document.getElementById("btn");
btn.onclick = function get() {
var x = document.getElementById("text").value; // --> HERE
document.getElementById("para").innerHTML = x;
};
get();
<input type="text" id="text" value="">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
Now when i assign the variable x inside the function ,after the ("text") i get the .nodeValue instead of getting the .value. Is that a problem with my code editor or i have an error, because every time i put a name inside the input field it shows the result inside the paragraph it appears and fast also disappears
So I see 2 problems here:
You didn`t close your script tag.
You are calling get(); but the function does not exist in that scope but is only assigned in the onclick event.
This should do the trick:
var btn=document.getElementById("btn");
btn.onclick = function get() {
var x = document.getElementById("text").value;
document.getElementById("para").innerHTML = x;
};
<input type="text" id="text" value="HELLO">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
I have preset the value to "HELLO", but you can change it as you want, and it will deliver the value requested when clicking on the button.
I think your only problem may have been how you were declaring the event listener, I declared it as an event listener on the button listening to the 'click' event.
I also edited 'x' to be 'userInput' so it is more clear what it is trying to achieve.
var btn = document.getElementById("btn");
btn.addEventListener('click', function () {
var userInput = document.getElementById("text").value;
document.getElementById("para").innerHTML = userInput;
});
var btn=document.getElementById("btn");
btn.onclick = function () {
var x = document.getElementById("text").value; // --> HERE
document.getElementById("para").innerHTML = x;
};
btn.onclick()
<input type="text" id="text" value="hello">
<input type="submit" value="submit" id="btn">
<p id="para"></p>
This is a working example of what you are trying to do. You can't declare a function in that context as it's anonymous. My example works perfectly, but you should do something more like
function get() {
//Do something
}
btn.onclick = get;
get();
I am not sure whether this will solve or not. However, I suggest you by giving an onclick event inside the input tag.
<input type="submit" value="submit" id="btn" onclick="get()">
<script>
function get() {
var x = document.getElementById("text").value;
document.getElementById("para").innerHTML = x;
}
</script>`

How to use implement a text input form using JavaScript in HTML

I am trying to use JavaScript in an online examination assignment in HTML. As a requirement of the project, we have to use text input forms as well as radio buttons and the like. I have dealt with the part of radio buttons but for some reason my text input forms do not work. My problem will be clearly stated using this code snippet from the main project:
<html>
<head>
<title></title>
<script type="text/javascript">
var test, name, matr, myname, count = 0;
function form(){
test = document.getElementById("test");
test.innerHTML = "Count = "+count;
test.innerHTML += "<form> \
First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check(){
myname = document.getElementsByName("name");
if (myname[1].value == "myname")
{
count++;
}
form();
}
window.addEventListener("load", form, false);
</script>
</head>
<body>
<div id = "test"></div>
</body>
</html>
What this code aims to do is that when the user inputs "myname" into the form called 'First name' and clicks 'Submit', the counter on the top should increment.
Can someone please shed some light on what I am doing wrong and how it may be resolved.
As Pluto mentioned, arrays in javascript start at 0. You can also look at tinkering with the form element. It is not closed nor is the type, get or post specified. I got it working in the example below by removing the form completely. This is because the button press was trying to submit the form and therefore load a new page.
https://jsfiddle.net/jpm68eub/
var test, name, matr, myname, count = 0;
function form() {
test = document.getElementById("test");
test.innerHTML = "Count = " + count;
test.innerHTML += "</br> First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check() {
myname = document.getElementsByName("name");
if (myname[0].value == "myname") {
count++;
}
form();
}
form();
you need to prevent the default action of the onclick event. To do this, try something like this:
function check(e){
e.preventDefault();
myname = document.getElementsByName("name");
if (myname[0].value == "myname")
{
count++;
}
form();
}
the above user was also correct about where javascript arrays start (they start at 0)

Value will blink only once at the html text box

while loop in javascript
function calc(){
var one = document.getElementById("fv").value;
var two = document.getElementById("sv").value;
var one1 = parseInt(one);
var two1 = parseInt(two);
var total = 0;
if(one1<=two1){
while (one1 <= two1){
total = total+one1;
one1++;
total=total;
}
document.getElementById("tv").value = total;
}}
calc() //call function
</script>
<form>
There are some confusion using while loop in java script. can i use while loop for those type of calculation?
<p>"Calculation of sum between two numbers"</p>
<h5>First Number</h5><input type ="text" value="1" name="firstv" id="fv"><br>
<h5>Second Number</h5><input type="text" value="100" name="sectv" id="sv"><br>
<h5>Value</h5><input type="number" value= "" name="tv" id="tv"><br>
<button onclick="calc()" value="click">Calculate</button><br>
</form>
</body>
</html>
You need to stop the button from actually submitting the form. If you make sure that your Javascript function appears before your html and your button looks like this:
<button onclick="calc(); return false;" value="click">Calculate</button>
Then it should work properly
If you need to call the first calc() before the button is clicked, you need to do it when the document is ready:
document.addEventListener("DOMContentLoaded", function(event) {
calc();
});
Example

Update a Element's Value On An Interval

I just want a temperature counter, to show in the div "display". The default temp is 7.2, and whenever I submit another temp, it slowly decrements (0,2 per 5 minutes) to that preferred temp. Can you help me out? I am a beginner so please bear with me.
What is wrong with this code?
JavaScript:
var temp = 7.2;
var loop = setInterval(cooler, 300000);
function cooler()
{
document.getElementById("display").innerHTML = temp-0,2;
setInterval(loop);
}
function abortTimer()
{
clearInterval(loop);
}
HTML:
<body>
Current temp <div id="display"> </div> <br>
<form>
Set temp: <input type="text" id="setTemp">
<input type="submit" value="Submit" onClick=cooler();>
</form>
</body>
There was a few things wrong with the code.
You decremented the value of temp but never update the variable. (temp)
By using setInterval you only need invoke it once. Once you clearInterval however you will need to call it again.
I changed the code a bit, updating variable names to something more appropriate. The code could definitely use some more love, but I kept my changes simple so you could follow along.
JavaScript:
var currentTemp = 7.2;
var loop = setInterval(cooler,1000);
function cooler()
{
currentTemp = currentTemp - 0.2;
document.getElementById("display").innerHTML = currentTemp;
}
function setTemp()
{
var input = document.getElementById('setTemp');
currentTemp = parseInt(input.value);
input.value = '';
}
function abortTimer()
{
clearInterval(loop);
}
//Wire click event to the submit button
document.getElementById('submit').addEventListener('click', function()
{
setTemp();
});
HTML:
<body>
Current temp <div id="display">
</div>
<br>
<form>
Set temp: <input type="text" id="setTemp">
<input id="submit" type="button" value="Submit">
</form>
</body>
See the link below for a sample of the code running at 1 second updates.
http://jsbin.com/zibuzuza/1/edit
startChange = function(){
var v,nt,diff,timelapse,decrease,decreaseit,loop;
v = d.value;
nt = t.value;
diff = v-nt;
timelapse = 500; //set to whatever you like
decrease = .2;
decreaseit = function(){
var v = d.value;
if(v>=(nt+decrease)){
loop = setTimeout(function(){
d.value = (v-decrease).toFixed(1);
decreaseit();
},timelapse)
} else clearInterval(loop);
}
decreaseit();
}
s.onclick = startChange;
Using setTimeout to call its parent function if conditions are met, else clearInterval
Using . (numbers with decimals), you're going to run into the whole parseFloat problem. It's hard to work with. Not a stunning example, but the basic framework : http://jsfiddle.net/wYn6J/1/

Categories

Resources