How do i find a factor of an integer in javascript? - javascript

I need to create a calculator where the user inputs a number, and it calculates the factors, cube and square of the given number.
Below is the code i am using.. I have NO idea how to work out the factor. Any advice would be appreciated.
document.getElementById('calculate').addEventListener('click', estimateTotal);
function estimateTotal(event) {
event.preventDefault();
var initial2 = document.getElementById('initial').value;
document.getElementById('factor').value = 0;
document.getElementById('sqaure').value = initial2 * initial2;
document.getElementById('cube').value = initial2 * initial2 * initial2;
}
<form id="calculator" method="POST">
<p>Please enter a number between 0 and 50 <input name="initial" id="initial" type="text" size="20" required><button id="calculate">Calculate</button></p>
<p>The Factorial of your number is: <input name="factor" id="factor" class="factor" type="text" size="20"></p>
<p>The Square of your number is:<input name="sqaure" id="sqaure" class="sqaure" type="text" size="20"></p>
<p>The Cube of your number is:<input name="cube" id="cube" class="cube" type="text" size="20"></p>
</form>

**recursive JavaScript function factor(n)**
**Check this link:** **http://www.javascripter.net/math/primes/factorization.htm**
function factor(n) {
if (isNaN(n) || !isFinite(n) || n%1!=0 || n==0) return ''+n;
if (n<0) return '-'+factor(-n);
var minFactor = leastFactor(n);
if (n==minFactor) return ''+n;
return minFactor+'*'+factor(n/minFactor);
}

try this for both factor and factorial
document.getElementById('calculate').addEventListener('click', estimateTotal);
function estimateTotal(event) {
event.preventDefault();
var initial2 = document.getElementById('initial').value;
document.getElementById('Factorial').value = fact(initial2);
document.getElementById('factor').value = factors(initial2);
document.getElementById('sqaure').value = initial2 * initial2;
document.getElementById('cube').value = initial2 * initial2 * initial2;
}
function fact(n)
{
if(n == 0)
return 1;
else
return (n*fact(n-1));
}
function factors(num)
{
var
n_factors = [],
i;
for (i = 1; i <= Math.floor(Math.sqrt(num)); i += 1)
if (num % i === 0)
{
n_factors.push(i);
if (num / i !== i)
n_factors.push(num / i);
}
n_factors.sort(function(a, b){return a - b;}); // numeric sort
return n_factors;
}
<p>Please enter a number between 0 and 50 <input name="initial" id="initial" type="text" size="20" required><button id="calculate">Calculate</button></p>
<p>The Factorial of your number is: <input name="factor" id="Factorial" class="factor" type="text" size="20"></p>
<p>The Factor of your number is: <input name="factor" id="factor" class="factor" type="text" size="20"></p>
<p>The Sqaure of your number is:<input name="sqaure" id="sqaure" class="sqaure" type="text" size="20"></p>
<p>The Cube of your number is:<input name="cube" id="cube" class="cube" type="text" size="20"></p>

Related

Using JS to show HTML output of calculation

I am trying to build a calorie calculator using HTML and JS and am currently struggling to show the output on screen (or via console.log). I know I'm doing something very basic quite wrong but can't currently pinpoint what that is.
Here's both my HTML and JS code below:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
function calcBMR(gender, weightKG, heightCM, age) {
// Calculate BMR
if (gender = 'male') {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Several things need to be modified in order to achieve your desired result.
The line document.getElementById("bmrForm").addEventListener("submit", calcBMR); is not needed because we can pass in a function directly to the onsubmit attribute of the form element.
The gender, weightKG, heightCM, and age parameters are not automatically passed in to the calcBMR function. The values need to be retrieved from the document.
The BMR variable needs to be defined above the if/else block because of scoping.
A return statement needs to be added to the onsubmit attribute so that the form does not submit and refresh the page. Alternatively, if the desired effect is to update the text on the screen, a button element with a click event handler added to it may be a better option that a form with a submit handler.
Strings are compared using == or === in JavaScript. Therefore, the gender = 'male' part needs to be changed to gender === 'male'.
In order to update the output, the element's textContent can be changed with document.getElementById("output").textContent = BMR.
Below is the code with the changes listed above.
function calcBMR() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let BMR;
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
document.getElementById("output").textContent = BMR;
return false;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="return calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
First, you are using a button with a type="submit", which is used to submit form data to a resource that will receive it and process it. In this case, you probably just want a button with type="button" that will only do what you've configured it to do (show the results on the screen).
After making that change, you should populate a pre-existing, but empty element with the result.
But you do have an issue with how and where you are declaring BMR. The let declaration should be outside of the if/then code but inside the function so it has scope throughout the function.
Also, your button's id is incorrect in the event handler setup.
Next, any value that you get from an HTML element will be a string and if you intend to do math with that value, you'll need to convert it to a JavaScript number. There are several ways to do this, but one shorthand way is to prepend the value with a + as you'll see I've done below.
Also, if someone were to type Male into the gender textbox, your code would not process it as a male because your code only checks for male, not Male. By forcing the input to lower case, your code will work (provided they spell male correctly). Preferably, you'd use a set of radio buttons or a drop down list for the user to choose from.
And, in conjunction with that, JavaScript uses = for assigning a value, not comparison. For loose equality (automatic type conversion) use == and for strict equality (no type conversion), use ===.
let out = document.getElementById("output");
let gender = document.getElementById("gender");
let height = document.getElementById("height");
let weight = document.getElementById("weight");
let age = document.getElementById("age");
// If you want to pass arguments to the event handler, you need to wrap the handler call in another function
document.getElementById("submitBtn").addEventListener("click", function(){calcBMR(gender.value.toLowerCase(), +weight.value, +height.value, +age.value)});
function calcBMR(gender, weightKG, heightCM, age) {
let BMR = null; // Declare the variable in the function scope
console.log(gender, weightKG, heightCM, age);
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="button" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Working Codepen
There are a few fundamental flaws in your code. Having said that, studying this will really give you a proper understanding of Javascript.
HTML:
<body>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?" name="gender">
<input type="number" id="weight" placeholder="Weight in KG" name="weight">
<input type="number" id="height" placeholder="Height in CM" name="height">
<input type="number" id="age" placeholder="How old are you?" name="age">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Javascript:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.querySelector('#output')
function calcBMR(e) {
e.preventDefault();
output.innerText = ''
const formData = new FormData(e.target)
const { age, gender, height, weight} = Object.fromEntries(formData);
let BMR = 0
// Calculate BMR
if (gender === 'male') {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) + 5;
} else {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) - 161;
}
output.innerText = BMR
}
You can remove the line document.getElementById("bmrForm").addEventListener("submit", calcBMR);
You can pass event to onsubmit - <form id="bmrForm" onsubmit="calcBMR(event)">
function calcBMR(e) {
e.preventDefault();
var elements = document.getElementById("bmrForm").elements; // logic to get all form elements
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.id] = item.value;
}
const {gender, weight, height, age } = obj; //Get values from obj
// Calculate BMR
let BMR = '';
if (gender === 'male') {
BMR = 10 * weight + 6.25 * height - 5 * age + 5;
} else {
BMR = 10 * weight + 6.25 * height - 5 * age - 161;
}
console.log(BMR);
}
The BMR is in the if tree, it must be in parent.
Try this!
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.getElementById('output');
function calcBMR(event) {
// Get the [gender, weightKG, heightCM, age] value
let gender = document.getElementById('gender').value;
let weightKG = document.getElementById('weight').value;
let heightCM = document.getElementById('height').value;
let age = document.getElementById('age').value;
// Set default BMR to 0
let BMR = 0;
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.innerText = BMR;
// Cancel form submit
event.preventDefault();
return;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
I used a selector instead of the text field for the gender.
I used form.elements to get the values from the form.
I used event.preventDefault(); to prevent the form from redirecting on submit.
// your form
var form = document.getElementById("formId");
var DoMagic = function(event)
{
event.preventDefault();
var elements = form.elements;
if (elements["gender"].value == "male")
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value + 5;
}
else
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value - 161;
}
document.getElementById("result").textContent = "Result: " + result;
}
// attach event listener
form.addEventListener("submit", DoMagic, true);
<form id = "formId">
<label>Gender</label>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label>Weight (kg)</label>
<input name="weight" type="number">
<br>
<label>Height (cm)</label>
<input name="height" type="number">
<br>
<label>Age (years)</label>
<input name="age" type="number">
<br>
<input type="submit" value="Do Magic!">
</form>
<span id='result'> </span>
Try this one, you are almost done, just by getting value from the input when user clicks the button.
But I have to notice you that submit button will immediately redirect to a new page, you should use click instead if you want to show yourself result.
document.getElementById("submitBtn").addEventListener("click",function(){
let gen = document.querySelector('#gender').value
let weight = document.querySelector('#weight').value
let height = document.querySelector('#height').value
let ages = document.querySelector('#age').value
calcBMR(gen,weight,height,ages)
})
function calcBMR(gender, weightKG, heightCM, age) {
let BMR
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
document.querySelector('#output').textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>

How can I display all guessed numbers in this lottery function?

I've created some simple lottery function in JS. All works fine.
The only issue I'm facing is how to display all numbers which have been guessed?
I have 6 independent spaces where numbers must be provided and my goal is to display the rolled number from random space, it must be just provided in one of the 6 spaces. That works for me, but only 1 number displays.
I'm looking for solution how to display all the guessed numbers?
function losowanie1() {
var wybor = 6;
var dostepne = 6;
r = new Array(dostepne)
var xd0 = document.getElementById("pole1").value
var xd1 = document.getElementById("pole2").value
var xd2 = document.getElementById("pole3").value
var xd3 = document.getElementById("pole4").value
var xd4 = document.getElementById("pole5").value
var xd5 = document.getElementById("pole6").value
y = new Array(6)
y[0] = xd0
y[1] = xd1
y[2] = xd2
y[3] = xd3
y[4] = xd4
y[5] = xd5
z = new Array(6)
for (var i = 0; i <= dostepne - 1; i++) {
r[i] = Math.floor((Math.random() * (49 - 1)) + 1);
if ((y[i] == r[0]) || (y[i] == r[1]) || (y[i] == r[2]) || (y[i] == r[3]) || (y[i] == r[4])) {
document.getElementById("zatw").innerHTML = y[i]
}
}
document.getElementById("wysw").innerHTML = r;
}
<div id="wysw"></div>
<div id="dupa">
<input type="text" id="pole1" /><input type="text" id="pole2" /><input type="text" id="pole3" /><input type="text" id="pole4" /><input type="text" id="pole5" /><input type="text" id="pole6" />
<br></br>
<input type="reset" id="tak" value="zatwierdz" onclick="losowanie1();" />
<br></br>
<div id="zatw"></div>
What the below still misses is to make sure the user don't repeats numbers in the inputs.
I won't do that since I would neither use inputs for that purpose, but rather predefined checkboxes (yes, 38 checkboxes) and make sure , on submit, exactly 6 are checked.
Anyways, hope this might be helpful:
function lottoGenerate(min, max) {
// Shuffle: https://stackoverflow.com/a/6274381/383904
const a = Array.from({length: max}, (_, v) => v + 1);
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a.slice(0, min);
}
function play() {
const guessed_nums = [];
const lotto_nums = lottoGenerate(6, 38); // Generate 6 random unique lotto numbers
const player_nums = Array.from(document.querySelectorAll('.num')).map(el => {
const n = parseInt(el.value, 10);
const isGuessed = lotto_nums.includes(n);
if (isGuessed) {
guessed_nums.push(n); // Insert the guessed number!
el.style.background = 'lightgreen';
} else {
el.style.background = 'red'
}
return n
});
document.getElementById('gen').textContent = lotto_nums.join(', ');
document.getElementById('player').textContent = player_nums.join(', ');
document.getElementById('response').innerHTML = `
You guessed ${guessed_nums.length} numbers!<br>
The numbers are: ${guessed_nums.join(', ')}
`;
}
document.getElementById('play').addEventListener('click', play);
<input class="num" type="number" min=1 max=38 value="1">
<input class="num" type="number" min=1 max=38 value="2"><br>
<input class="num" type="number" min=1 max=38 value="3">
<input class="num" type="number" min=1 max=38 value="4"><br>
<input class="num" type="number" min=1 max=38 value="5">
<input class="num" type="number" min=1 max=38 value="26"><br>
<button id="play">PLAY LOTTO 6/38</button>
<div>Numbers: <span id="gen"></span></div>
<div>User played: <span id="player"></span></div>
<div id="response"></div>

How to limit two inputs with custom maxlength?

How to limit two inputs with custom maxlength ?
I am setting a custom limit $limit = "500"; and trying to limit user words in two inputs. I want to limit first input maxlength and count words in first input, than limit second input maxlength with words left from my custom limit.
I want to set length together max length 500, one can have max 100 and one can have max 400.
and if first input has less words than 100, then add rest of the words left to the second input max length.
like : first input has 95 words in, 5 words left to reach limit.
then change second input maxlentgh to 405,
I create inputs like this :
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function() {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("title"));
function validateLength(el, word_left_field, len) {
document.all[word_left_field].value = len - el.value.length;
if (document.all[word_left_field].value < 1) {
alert("You can add max " + len + " words .");
el.value = el.value.substr(0, len);
document.all[word_left_field].value = 0;
return false;
}
return true;
}
<input type="text" id="title" name="title" maxlength="100" onChange="return validateLength(this, 'word_left', 100);" onKeyUp="return validateLength(this, 'word_left', 100);">
<input type="text" name="word_left" value="100" style="width: 25;" readonly="true" size="3">
<input type="text" id="subject" name="subject" maxlength="400" onChange="return validateLength(this, 'word_left', 400);" onKeyUp="return validateLength(this, 'word_left', 400);">
<input type="text" name="word_left" value="400" style="width: 25;" readonly="true" size="3">
so total of both inputs is 500.
I tried to set html 5 attributes pattern=".{59,60}" but they are same as setting attrbutes min and length.
But my javascript is limiting first input.
I tried several methods but didn't have a chance to make it work, would be to long question I didnt put all on here.
I belive that you need something like this:
var _maxLength = 500;
var _lengthInput = 0;
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var p = document.getElementById("total");
p.innerHTML = _maxLength;
input1.addEventListener("focus", function(e) {
this.maxLength = _maxLength + this.value.length;
_lengthInput = this.value.length;
});
input1.addEventListener("blur", function(e) {
if (_lengthInput == this.value.length)
return;
if (_lengthInput > this.value.length) {
_maxLength += _lengthInput - this.value.length;
} else {
_maxLength -= this.value.length - _lengthInput;
}
total.innerHTML = _maxLength;
});
input2.addEventListener("focus", function(e) {
this.maxLength = _maxLength + this.value.length;
_lengthInput = this.value.length;
});
input2.addEventListener("blur", function(e) {
if (_lengthInput == this.value.length)
return;
if (_lengthInput > this.value.length) {
_maxLength += _lengthInput - this.value.length;
} else {
_maxLength -= this.value.length - _lengthInput;
}
total.innerHTML = _maxLength;
});
Input 1 <input type="text" id="input1">
<br /> Input 2 <input type="text" id="input2">
<br />
<p>Characters remaining: <span id="total"></span> </p>
I hope below code helps you,
$(document).ready(function () {
$("#subject").on("keypress", function () {
var titleLength = $("#title").val().length;
var titleMaxLength = $("#title").attr("maxLength");
var titleWordLeft = titleMaxLength - titleLength
var subjectLength = $("#subject").data("charlength");
var subjectMaxLength = titleWordLeft + subjectLength;
$("#subject").attr("maxLength",subjectMaxLength);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="title" name="title" maxlength="100">
<input type="text" name="word_left" value="100" style="width: 25;" readonly="true" size="3">
<input type="text" id="subject" name="subject" data-charlength="400">
<input type="text" name="word_left" value="400" style="width: 25;" readonly="true" size="3">

Use Javascript to Make Calculator

Good Day - I am Learning Javascript, I am trying to create a Calculator to calculate ampere-turn to magnetize a tool (it's related to my job.) I am trying to use some formulas to calculate this ampere-turn. The code seems fine to me, but it's not working. I put some values in the form, and click button submit, but no result found and i don't know why this happens.
I am sharing my code here for your kind review. and help me to fix this problem.
thank you.
function ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
if(factor <= 0.1)
{
ans = 45000/ldratio*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}
<form name="ampereturn">
<div class="w3-half w3-margin-top">
<label>Tool OD:</label>
<input id="inputod" class="w3-input w3-border" type="number" placeholder="Input Tool Outer Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Tool Lenght:</label>
<input id="inputlen" class="w3-input w3-border" type="number" placeholder="Input Tool Length">
</div>
<div class="w3-half w3-margin-top">
<label>Coil ID:</label>
<input id="Inputid" class="w3-input w3-border" type="number" placeholder="Input Coil Internal Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Coil Turn:</label>
<input id="Inputturn" class="w3-input w3-border" type="number" placeholder="Input Number of turn in coil:">
</div>
<div class="w3-half w3-margin-top">
<label>Required Ampere:</label>
<p id="sum"></p>
</div>
<button type="button" onclick="ampereturn()">Submit</button>
</form>
<br><hr>
thank you in advance. ....
Change the function name which is same as the form name.
Change Inputturn to InputTurn in the if condition.
Required Code:
function Ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else if(factor <=0.1)
{
ans = 45000/ldratio*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}

How to switch functions javascript

I'd like to make something small. When you enter Celsius, the program should calculate Fahrenheit and vice-versa. But when I enter the celsius and click the button it does the vice-versa aswell. Since I'm a beginner I don't really know how not to execute function2 if function1 activates. My javascript looks like this:
JS:
function Omrekenen() {
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
var r1 = (celsius * 1.8) + 32;
var r2 = (fahrenheit / 1.8) - 32;
}
function Leeg1() {
document.getElementById('Fahrenheit').value = "";
}
function Leeg2() {
document.getElementById('Celsius').value = "";
}
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen(); Vast();" class="Button">
</div>
Here's one way of doing this.
Note that I'm checking for the length of the value from the input. You can't check the truthiness (if (celsius) ...) in this case, since a value of 0 is valid, but would evaluate to false. Checking the length should work for each case.
function Omrekenen() {
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
if (celsius.length !== 0) {
document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
} else if (fahrenheit.length !== 0) {
document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
}
}
function Leeg1() {
document.getElementById('Fahrenheit').value = "";
}
function Leeg2() {
document.getElementById('Celsius').value = "";
}
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen();" class="Button">
</div>
You can use a state variable also, but you'd also want to handle the paste action in that case.
<script>
var isCalculatingCelsius;
function Omrekenen()
{
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
if (isCalculatingCelsius){
document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
} else {
document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
}
}
function Leeg1(){
isCalculatingCelsius = false;
document.getElementById('Fahrenheit').value = "";
}
function Leeg2(){
isCalculatingCelsius = true;
document.getElementById('Celsius').value = "";
}
</script>
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup="Leeg1()">
Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen()" class="Button">
</div>

Categories

Resources