Problem:
,
i want the output like this picture
i don’t know how the result display in text box ,and on select the temperature.
`
Temperature Converter
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 30px;
border-width: 12cap;
border-color: black;
}
label {
display:ruby-base;
margin-bottom: 10px;
}
input {
padding: 10px;
margin: 20px;
}
button {
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
}
#result {
font-size: 18px;
margin-top: 20px;
}
</style>
<h2>Temperature Converter</h2>
<label for="temperature">Temperature:</label>
<input type="text" id="temperature" placeholder="Temperature">
<br></br>
<select id="unit">
<option value="celsius">C</option>
<option value="fahrenheit">F</option>
</select><br></br>
<br></br>
<div id="result"></div>
<script>
function convertTemperature() {
// Get input values
var temperature = parseFloat(document.getElementById('temperature').value);
var unit = document.getElementById('unit').value;
// Check if the input is a valid number
if (isNaN(temperature)) {
alert("Please enter a valid temperature!");
return;
}
// Convert temperature based on the selected unit
var result;
if (unit === 'celsius') {
result = (temperature * 9/5) + 32;
document.getElementById('result').innerHTML = temperature + result.toFixed(2) ;
} else {
result = (temperature - 32) * 5/9;
document.getElementById('result').innerHTML = temperature + result.toFixed(2) ;
}
}
</script>
`
pleas help me with this
i can’t find the answer
Solution:
hello my friend your UI is little confusing because when you want convert sth to sth it is better for your user to konw which unit is converted to another unit. so it better to write in option tag sth like this “c => f” or “f => c”.
must easiest way to show the result is to add eventListener to your (id =”temperature”) with change value. like below
enter code here
document.getElementById('temperature').addEventListener('change', convertTemperature);
and you can update your result at the end of you “temperature” function like this
enter code here
if (unit === 'celsius') {
let farenhite = (temperature * 9/5) + 32;
result = Number(temperature).toFixed(2) + Number(farenhite).toFixed
document.getElementById('result').innerHTML = Number(result).toFixed(2) ;
} else {
let celsius = (temperature - 32) * 5/9;
result = Number(temperature).toFixed(2) + Number(celsius).toFixed;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
after this your decimal in the result will fix with two place.