Reload individual input with JS - javascript

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">

Related

2 textbox that copies each other value while typing, but the other textbox has no comma

I'm currently working with 2 textboxes that copies each other values. But the thing is, my 1st textbox has an autocomma. How could I make my 2nd textbox ignore the comma?
For example. My first textbox value is 1,000 then my 2nd textbox
value should be 1000.
HTML
<input type="text" value="" id="textbox1"/>
<input type="text" value="" id="textbox2"/>
Script
//this function is for my autocomma
function updateTextView(_obj){
var num = getNumber(_obj.val());
if(num==0){
_obj.val('');
}else{
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#textbox1').on('keyup',function(){
updateTextView($(this));
});
});
//this function copies the textbox1 values to textbox value 2
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
You modify the function updateTextView as below:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
$("#textbox2").val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
And then remove the following:
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
In plain JS:
Try the onkeyup() event added to the first textbox. Then replace all commas in the value of the first box with nothing using value.replace(/,/g, ""). And then copy the value of the first input
function update(input) {
var value = input.value.replace(/,/g, "");
document.getElementById("second-textbox").value = value;
}
<input onkeyup="(update(this))" />
<input id="second-textbox" />
to the second.

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');
}

Make sure that an event execute after the actions of another one

Let's say that I've a file where I bind an event to some inputs, for parse and format date with moment.js, for example:
// plugins.js
$('.date').on('focusout', function() {
var thisInput = $(this);
thisInput.val( moment(thisInput.val()).format('YYYY-MM-DD') );
});
In my html file I've a script after the plugins.js call, in this script I use the parsed date to calculate the age from the date, assuming that the function has already executed in plugins.js:
<form>
<div class="form-group">
<label for="birth-date-input">Birth date</label>
<input type="text" id="birth-date-input" class="date">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="text" id="age">
</div>
</form>
<script src="plugins.js"></script>
<script>
jQuery(document).ready(function($) {
$('#birth-date-input').on('focusout', function() {
var thisInputVal = $(this).val();
var birthDate = moment(thisInputVal, 'YYYY-MM-DD');
var age = moment().diff(birthDate, 'years');
$('#age').val( age );
});
});
</script>
In my ideal word the .val() of the second script would be the assigned in the first, the parsed date. But the fact is that in both cases the value is the same, the only way I could make this work was with a dirty setTimeout().
$('#birth-date-input').on('focusout', function() {
setTimeout(function() {
var thisInputVal = $(this).val();
var birthDate = moment(thisInputVal, 'YYYY-MM-DD');
var age = moment().diff(birthDate, 'years');
$('#age').val( age );
}, 100);
});
Is there an alternative way to do this? To make sure that an event execute after the actions of another one [without setTimeout]...
You can call function which you want to execute first inside the second function before any other code. SO it has to execute first like.
function a()
{
alert("first");
return true;
}
function b
{
b();
alert("second");
}
or you can set an hidden variable on execution of first functin and check whether it is set or not in second one.

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

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