Basic javascript Fahrenheit/Celsius calculator

后端 未结 2 1037
既然无缘
既然无缘 2021-01-13 13:47

I\'m trying to do a Celsius/Fahrenheit conversion calculator, with a button for each conversion and the result being displayed in the appropriate textbox. I must be missing

相关标签:
2条回答
  • 2021-01-13 14:29

    You are querying the DOM with the document.getElementById() function, but both input elements don't currently have an id attribute only a name attribute. So in your example, there are no elements that actually match the IDs you're passing to the function.

    You should set the id attributes of both elements like so:

    <input id="fTemp" name="fTemp" type="text">
    
    <input id="cTemp" name="cTemp" type="text">
    
    0 讨论(0)
  • 2021-01-13 14:34

    You have a few errors. See this corrected jsFiddle example.

    1. Your input boxes were missing IDs that you were trying to reference with document.getElementById
    2. Your HTML was improperly closed.
    3. Your buttons were missing types which makes them default to submit when you really wanted just button
    4. To prevent the form from actually being submitted you should return false.

    JavaScript

        function convertToC() {
            var fTempVal = parseFloat(document.getElementById('fTemp').value);
            var cTempVal = (fTempVal - 32) * (5 / 9);
            document.getElementById('cTemp').value = cTempVal;
            return false;
        }
    
        function convertToF() {
            var cTempVal = parseFloat(document.getElementById('cTemp').value);
            var fTempVal = (cTempVal * (9 / 5)) + 32;
            console.log(fTempVal);
            document.getElementById('fTemp').value = fTempVal;
            return false;
        }
    

    HTML

    <form name="conversionForm">
        <table border="1">
            <tbody>
                <tr>
                    <td>Fahrenheit</td>
                    <td>
                        <input name="fTemp" id="fTemp" type="text" />
                    </td>
                    <td>
                        <button type="button" onclick="convertToC();return false">Convert to Celsius</button>
                    </td>
                </tr>
                <tr>
                    <td>Celsius</td>
                    <td>
                        <input name="cTemp" id="cTemp" type="text" />
                    </td>
                    <td>
                        <button type="button" onclick="convertToF();return false">Convert to Fahrenheit</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
    
    0 讨论(0)
提交回复
热议问题