,
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
3
Answers
You have defined a function
convertTemperature()
but never called it.You can create a button with
onclick
attribute set toconvertTemperature()
so that, that function is called when you click on that button.It will look something like this –
Add event listeners to your input and dropdown that will call your function.
You just need to call the function on your input and select element, try to replace your code like this,
<select id="unit" onchange="convertTemperature()">
and also on your input component<input type="text" id="temperature" placeholder="Temperature" onkeypress="convertTemperature()">