Update a Element's Value On An Interval - javascript

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/

Related

Reload individual input with JS

I'd like to refresh an input field every second while leaving the rest of the page untouched. Is there a way to do this with Javascript? I'm a little unsure how to write it, but I think it would look like..
var myVar;
function autoRefresh() {
myVar = setInterval(loadValue, 1000);
}
function loadValue() {
input.reload("reload").value
}
<input type="text" id="reload">
I'm sure the syntax is wrong, but any input would be great!
You're on the right track, but what should the field's value be when it is refreshed?
In this example, I'm turning the field into a clock by refreshing its value with the current time every second:
document.getElementById("loadTime").textContent = new Date().toLocaleTimeString();
var input = document.getElementById("reload");
setInterval(function(){
input.value = new Date().toLocaleTimeString();
}, 1000);
<div>Time page was loaded: <span id="loadTime"></span></div>
Current Time:<input type="text" id="reload">
var myVar;
var counter = 1;
var input = document.getElementById('reload');
function autoRefresh() {
myVar = setInterval(loadValue, 1000);
}
function loadValue() {
input.value = counter++;
}
autoRefresh();
<input type="text" id="reload">

How to take an input that is equal to 10 and perform a function that says awesome to the screen

I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}

JS | Receiving NaN as output when trying to pull content from text input

I'm new to JS and having trouble parseing text input into a calculation function. I must be doing something fundamentally wrong as I know the actual parse method is correct. I've been trying a bunch of different things but am kind of running around in circles at this point. I'm just making a simple celius/farenheit converter. Any help is greatly appreciated!
NOTE I'm trying to use pure JS only
<body>
<h2>Temperature Converter</h2>
<form>
<input id="degrees" type="text" size="5">
<input type="radio" value="celsius" name="one" id="celsius">Celsius
<input type="radio" value="farenheit" name="one" id="farenheit">Farenheit
<button id="equals" type="button">=</button>
<output id="output">
</form>
<script type="text/javascript" src="js/script2.js"></script>
</body>
var val = parseFloat(document.querySelector("#degrees").value);
var output = document.getElementById("output");
window.addEventListener("load", main);
function main() {
// listen for a click on the "equals" button
document.querySelector("#equals").addEventListener(
"click", function(){convert("val");});
}
function convert(val) {
var c = document.getElementById("celsius");
var f = document.getElementById("farenheit");
if (c.checked) {
toFarenheit(val);
console.log("celsius selected");
} else if (f.checked) {
toCelsius(val);
console.log("farenheit selected");
} else {
console.log("Select whether input is in celsius or farenheit.");
}
}
function toCelsius(val) {
output.value = (val - 32) / 1.8;
console.log(output.value);
}
function toFarenheit(val) {
output.value = val * 1.8 + 32;
console.log(output.value);
}
At this point
convert("val");
you give your convert() function the strings "val" to be used for conversion and not the variable. This leads to the NaN value in the computation later on.
You should move the line, where you retrieve the value val to inside the convert() function, so it will get updated upon the click. Currently you read the value just at startup (where it will most probably be empty) and never update it.
function convert() {
var c = document.getElementById("celsius");
var f = document.getElementById("farenheit");
var val = parseFloat(document.querySelector("#degrees").value);
if (c.checked) {
toFarenheit(val);
console.log("celsius selected");
} else if (f.checked) {
toCelsius(val);
console.log("farenheit selected");
} else {
console.log("Select whether input is in celsius or farenheit.");
}
}
Here is error
document.querySelector("#equals").addEventListener(
"click", function(){convert("val");});
Nedd
document.querySelector("#equals").addEventListener(
"click", function(){convert(val);});
Yip the first commenter to your answer was on the nose. You need to update your val variable on click. You can declare it up top and then update it in the function call, or just create it as a scoped variable in the click listener.
Working fiddle: https://jsfiddle.net/6s5nx7dn/

Character Counter for multiple text areas

I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>

Passing JQuery value to html and then tally the totals with onclick

I am trying to pass on JQuery values to hidden textboxes (to send as a form later) as well as divs t
hat displays on the front end. I also want to tally these items as the value is passed to them. I have Frankensteined this bit of code which passes on the value to the the input boxes and the divs and it also tallies them onclick. I am just struggling to get the sum to display in #total_div. Can anyone point me in the right direction please?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#my_div').click(function() {
$('#my_value_1').val("100");
$('#my_value_1_div').html( "100" );
$('#my_div').click(addNumbers('total'));
});
});
$(document).ready(function(){
$('#my_div_2').click(function() {
$('#my_value_2').val("200");
$('#my_value_2_div').html( "200" );
$('#my_div_2').click(addNumbers('total'));
});
});
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
</script>
<h2>My pretty front end</h2>
<div id="my_div">ADD THIS VALUE 1</div>
<div id="my_div_2">ADD THIS VALUE 2</div>
VALUE 1: <div id="my_value_1_div">VALUE 1 GOES HERE</div>
VALUE 2: <div id="my_value_2_div">VALUE 2 GOES HERE</div>
TOTAL: <div id="total_div">SUM MUST GO HERE</div>
<h2>My hidden Form</h2>
Value 1: <input type="text" id="my_value_1" name="my_value_1" value="0"/>
Value 2: <input type="text" id="my_value_2" name="my_value_2" value="0"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
Total: <input type="text" id="total" name="total" value=""/>
EDIT
Ok so thanks to the advice I got the above working but now I need to clear the amounts. This is what I have done, it is almost there I think but I'm getting the incorrect sum.
$('#clear').click(function() {
$('#my_value_1').val('0');
$('#my_value_1_div').html( "0" );
$('#clear').click(minusNumbers('total'));
});
function minusNumbers()
{
var minval1 = parseInt(document.getElementById("my_value_1").value);
var minval2 = parseInt(document.getElementById("total").value);
var minansD = document.getElementById("total");
minansD.value = minval2 - minval1;
$('#total_div').text(minansD.value);
}
Update #total_div text in addNumber function as,
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
$('#total_div').text(ansD.value);
}
Demo
replace:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
with:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD = val1 + val2;
$('#total').val(ansD);
}
click(addNumbers('total')); first calls addNumbers with an unused parameter 'total' then gets the return value of addNumbers (null or undefined) and sets that as the click() handler for the next click.
I think you probably meant
$('#my_div').click(addNumbers);
that means, "run the addNumbers function, defined below, next time I click my_div".
or just
addNumbers();
that means, "run the addNumbers function now" (at the first click)
Note though that when you click and call addNumbers, one of the numbers may not yet be copied, so you would be adding 100+"" or ""+200 so you really have to think about what you want to do.

Categories

Resources