When the user enters value in feet, the application should calculate the meter equivalent and display the same in meter textfield.
Formula : 1ft = 0.3048m
When the user enters a value in the meter, the application should calculate the feet equivalent and display the same in feet text field.
Formula : 1m = 3.2808ft
Need to update both values simultaneously when I enter either of the input fields.
Here is my code:
function LengthConverter(val) {
var input2 = document.getElementById("meter").innerHTML = val / 3.2808;
console.log(input2);
val.value = input2.value;
}
<div class="container">
<div class='ftm'>
<label for="feet">Feet:</label><br>
<input id="feet" type="number" placeholder="Feet" onchange="LengthConverter(this.value)">
</div>
<div class='ftm'>
<label for="meter">Meter:</label><br>
<input id="meter" type="number" placeholder="Meters">
</div>
</div>
You can use element.addEventListener
to watch for changes to the elements, then run a function to update the other one
const feetInput = document.getElementById('feet');
const meterInput = document.getElementById('meter');
function updateMeter() {
meterInput.value = feetInput.value / 3.2808;
}
function updateFeet() {
feetInput.value = meterInput.value * 3.2808;
}
// an input event is similar to change but only fires when the actual
// contents of the input field change
feetInput.addEventListener('input', updateMeter);
meterInput.addEventListener('input', updateFeet);
<div class="container">
<div class='ftm'>
<label for="feet">Feet:</label><br>
<input id="feet" type="number" placeholder="Feet">
</div>
<div class='ftm'>
<label for="meter">Meter:</label><br>
<input id="meter" type="number" placeholder="Meters">
</div>
</div>
Try following :
function LengthConverter(val) {
var input2 = document.getElementById("meter").value = val / 3.2808;
console.log(input2);
val.value = input2.value;
}
<div class="container">
<div class='ftm'>
<label for="feet">Feet:</label><br>
<input id="feet" type="number" placeholder="Feet" onchange="LengthConverter(this.value)">
</div>
<div class='ftm'>
<label for="meter">Meter:</label><br>
<input id="meter" type="number" placeholder="Meters">
</div>
</div>