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

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.

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

Increment input field value with jQuery

I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});

JavaScript, document.getElementById not grabbing from form?

I'm attempting to create a datetime-local input that will submit into a function that will convert it into different types later on. I've been attempting to check whether the function I am using is receiving the user input by throwing it into an alert, however every time I get the alert, the information is not displayed, with "[object HTMLInputElement]" in its place. Clearly I must be doing something wrong if my bugtest isn't even working properly
Below is my form and my script.
<form>
Start Time:
<input type="datetime-local" id="start">
End Time:
<input type="datetime-local" id="end">
<input type="submit" value="Send" onclick="convert()">
</form>
<script>
function convert() {
var sd = new Date(); //start date
var sds = new String();
var ed = new Date(); //end date
var eds = new String();
var sd = document.getElementById("start");
alert(sd);
var sds = document.getElementById("end");
alert(sds);
}
</script>
Does anything obvious stick out?
Simply calling getElementById will return an HTMLInputElement object. To get its value, you need to call .value
var sd = document.getElementById("start").value;
and
var sds = document.getElementById("end").value;
You also declared the variable sd twice. Only once is necessary. This adds to the codebase and makes things less DRY. Also, instead of initializing a new string like this
var eds = new String();
Do this instead
var eds = "";
I updated and improved your code.
var startValue = document.getElementById("start-value");
var endValue = document.getElementById("end-value");
function convert() {
var sd = new Date(); // start date
var ed = new Date(); // end date
var eds = new String();
var sd = document.getElementById("start").value;
startValue.innerHTML = sd;
var sds = document.getElementById("end").value;
endValue.innerHTML = sds;
}
<form>
Start Time:
<input type="datetime-local" id="start">
End Time:
<input type="datetime-local" id="end">
<input type="submit" value="Send" onclick="convert()">
</form>
<p id="start-value"></p>
<p id="end-value"></p>
YOu have declared the same variable twice, var sd. one time you assigned it a Date() function and the second time you have assigned it a document.getElementByID(). and yes what the gental men said, innerHtml need to included to get the value of the field.
First the click event is not the right chooce for what you are trying to achieve. Second youll have to bind events on the inpits rather then the form. You probably want to use a on change event. I also highly recommend using socument states and wleventbindings.

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/

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Categories

Resources