0

我正在尝试制作一个表单,您可以在其中向文本框输入数字,并基于该文本响应将文本响应放入文本框中。这是我一直在努力工作的一个例子:

<html>
    <head>
        <script type="text/javascript">
            function calculate()
            {
                var ph = document.test.ph.value;
                if (ph > 7.45) {
                    var str = "Alkalosis";
                }
                else if (ph < 7.35) {
                    var str = "Acidosis";
                }
                else {
                    var str = "Normal";
                }
                document.test.acidalk.value = str;
            }
        </script>
    </head>
    <body>
        <form name="test">
            pH<input type="textbox" name="ph"><br>
            <input type="submit" value="Calculate"><br>
            <input type="textbox" id="acidalk" >
        </form>
    </body>
</html>

我想要实现的想法是,如果在第一个文本框中输入高于 7.45 的数字,单击按钮,然后在第二个文本框中输入“碱中毒”一词,但如果数字小于7.35,这个词改为“酸中毒”。

任何帮助将不胜感激

4

4 回答 4

0

嗯,你大部分都在那里。不要让按钮成为提交按钮,而是尝试

<input type="button" onclick="calculate();" value="Calculate" />
于 2012-12-13T00:58:16.127 回答
0

您的代码的基础这将是一种方法:

<html>
<head>
    <script type="text/javascript">
        function calculate(){
            var ph = document.getElementById('ph').value;
            if(ph > 7.45){
                var str="Alkalosis";
            }else if(ph < 7.35){
                var str="Acidosis";
            } else{
                var str="Normal";
            }
            document.getElementById('acidalk').value =str;
        }
    </script>
</head>
<body>
    pH<input type="textbox" name="ph"><br>
    <button onclick="calculate()">Calculate</button>
    <input type="textbox" id="acidalk" >
</body>
</html>

希望有帮助!

于 2012-12-13T01:03:21.557 回答
0

你有形式,你有功能,你只需要一种方法将它们联系在一起。通过指定calculate()为表单事件的事件处理程序来做到这一点submit。确保return false否则表单将被提交并且calculate()不会看到结果。

<form name="test" onsubmit="calculate(); return false">

jsfiddle.net/UhJG2

绑定到表单的submit事件而不是按钮的click事件具有在按下时调用函数的额外好处enter。它还确保表单不会被意外提交。

于 2012-12-13T01:10:22.197 回答
0

使用 jQuery:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>

<body>pH
    <input type="textbox" name="ph" id="ph">
    <br>
    <button id="calculate">Calculate Acid Level</button>
    <br />
    <input type="textbox" id="acidalk" value="" />
</body>
<script type="text/javascript">
    $("#calculate").click(function () {
        var ph = $("#ph").val();
        if (ph > 7.45) str = "Alkalosis";
        else if (ph < 7.35) var str = "Acidosis";
        else var str = "Normal";

        $("#acidalk").val(str);
    });
</script>
</html>
于 2012-12-13T01:46:31.477 回答