【问题标题】:Using JavaScript to gather user input for calculations使用 JavaScript 收集用户输入以进行计算
【发布时间】:2014-07-10 21:40:24
【问题描述】:

所以我一直在学习 JavaScript 语言的基础知识。到目前为止,一切都很好。我正在练习很多比较操作,以根据我的变量定义来理解各种计算和输出。

我可以定义 2 个变量并设置它们。这很简单。

var variable1 = 1; 
var variable2 = 2;

我可以使用 if/else 语句来比较 2 个变量值。

if (variable1 > variable2) {

  alert("The first variable is greater than the second.");

} else {

  alert("The second variable is greater than the first one.");

}

我理解这个简单的逻辑以及它是如何工作的。

我的问题是,如果我希望网页用户输入 2 个数字以便我可以计算它们(使用上述条件语句),我如何访问或定义作为用户输入结果的变量?到目前为止,我只能在 js 文件中自己定义变量。我将如何访问 javaScript 中的用户 html 输入以执行相同的计算?

我的第一个假设是我使用 getElementById 属性来访问 html 中 textarea 元素的值。但我不确定这将如何将 textarea 值存储为变量然后进行计算。我希望这是有道理的。

感谢那些愿意帮助我的人。我感谢您的时间很重要,这对你们中的许多人来说是一个非常基本的问题。

【问题讨论】:

  • 我不想发布这么简短的答案作为答案,因为其他人可能会花时间详细说明。 var variable1 = document.getElementById('inputfield1').value;
  • 这可能不是真的。 “第二个变量大于第一个变量。”因为给定子句,第二个变量大于等于第一个变量。
  • 当您刚开始学习从 HTML 表单输入中提取值之前,window.prompt() 可能是一个有用的拐杖。用法:variable1 = window.prompt("Enter a value for variable1:");

标签: javascript html conditional-statements


【解决方案1】:

View this working example

HTML

<input type="text" id="inputfield1" />
<input type="text" id="inputfield2" />
<button onclick="compare()">Compare</button>

JS

function compare(){
    var variable1 = parseInt(document.getElementById('inputfield1').value);
    var variable2 = parseInt(document.getElementById('inputfield2').value);
    if (variable1 > variable2) {
      alert("The first variable is greater than the second.");
    } else {
      alert("The second variable is greater than or equal to the first one.");
    }    
};

请记住,文本输入会以字符串形式返回。在这个例子中,我使用parseInt() 转换为整数。

【讨论】:

  • 谢谢。添加解析转换非常有用。就像是使用一个函数和onclick事件来比较结果。我正在一点一点地学习,但这有助于我将它们串在一起。 :)
  • 我意识到这只是教育实验,但如果您曾经在真实情况下使用过 parseInt,请务必先阅读它的工作原理。在我的回答中,我建议改为乘以 1。它不太可能以意想不到的方式失败(尽管它仍然可能)。例如:jsfiddle.net/eFkze/1
  • 那个小提琴的例子没有证明 parseInt() 失败。
【解决方案2】:

例如,您有一个 HTML 页面:

<html>
...
<!-- comment: make sure to include your script here as this is a common mistake -->
<body>
  <input type="text" id="text1ID" />
  <input type="text" id="text2ID" />
</body>
...
</html>

在您包含的 JavaScript 中,您可以这样做:

// getting the values:
var variable1 = document.getElementById('text1ID').value;
var variable1 = document.getElementById('text2ID').value;

// add logic to do something about the values:

if (variable1 > variable2) {

  alert("The first variable is greater than the second.");

} else {
  // fixed this according to comments
  // alert("The second variable is greater than the first one.");
  alert("The second variable is greater than OR equal the first one.");

}

【讨论】:

    【解决方案3】:

    HTML 代码

    <input type="text" id="ele1" name="ele1" />
    <input type="text" id="ele2" name="ele1" />
    

    对于 JavaScript,您可以使用 getElementById 访问具有指定 id 的元素

    var variable1 = document.getElementById("ele1").value;
    var variable2 = document.getElementById("ele2").value;
    

    对于 jQuery

    var variable1 =$("#ele1").val();
    var variable2 = $("#ele2").val();
    

    【讨论】:

    • 应该是 $("#ele1").val();# 符号。
    【解决方案4】:

    我会遵循 nmenego 的建议,但请记住,您从文本字段中获得的值本质上是字符串(而不是数字)。 Javascript 让您可以快速轻松地使用它,但这会导致不太理想的结果:

    考虑: http://jsfiddle.net/eFkze/

    alert("10" > "9")
    

    所以......你会想要收集这些值,然后最简单的方法是尝试将它们乘以 1。如果该值是“一些非数字的东西”,那么该操作的结果将失败,但如果它是“5”或“5.5”。

    【讨论】:

      【解决方案5】:

      而不是使用:

      var variable1 = 1;
      var variable2 = 2;
      

      使用:

      var variable1 = document.getElementById('inputfield1').value;
      var variable1 = document.getElementById('inputfield2').value;
      

      您将获得这些输入字段的值。但是您必须确保这些是您正在比较的数字,因为用户可能会输入您正在计算的数字值以外的任何值。所以你必须在比较之前做一些验证。

      【讨论】:

        【解决方案6】:

        在 Chrome 上试试这个,它完全符合 HTML5,试试非数字,看看会发生什么:

        <!DOCTYPE HTML>
        <html>
        <head>
        <title>Untitled Document</title>
        <script>
        function compare()
        {
            var variable1 = document.getElementById('firstNumber').value;
            var variable2 = document.getElementById('secondNumber').value;
            if (variable1 > variable2) {
                alert("The first variable is greater than the second.");
            } else if (variable1 < variable2)
            {
                alert("The second variable is greater than the first one.");
            }  else 
            {
                alert("They are equal");
            }
        }
        </script>
        </head>
        <body>
        <form onsubmit="compare();return false;">
        First Number: <input type="number" id="firstNumber" name="firstNumber" required>
        Second Number: <input type="number" id="secondNumber" name="secondNumber" required>
        <input type="submit" value="Submit">
        </body>
        </html>
        

        【讨论】:

          【解决方案7】:

          HTML

          <input id='value1' type='text' placeholder='enter value1' />
          <br/>
          <input id='value2' type='text' placeholder='enter value2' />
          <br/>
          <button id='calculate'>Calculate</button>
          

          JavaScript

          var button = document.getElementById('calculate');
          button.addEventListener('click', calculate, false);
          
          function calculate() {
              var value1 = parseFloat(document.getElementById('value1').value);
              var value2 = parseFloat(document.getElementById('value2').value);
          
              if (value1 > value2) {
                  alert("The first variable is greater than the second.");
              } else {
                  alert("The second variable is greater than or equal to the first one.");
              }
          }
          

          此示例为您提供了您正在寻找的内容。它还将 HTML 与 JS 代码分开,您可以在 JavaScript 代码中挂钩 click 事件,而不是 HTML onclick 标记。

          当然,您必须注意用户的有效输入,因此数字字段中没有文本,但那是另一回事了。

          你可以在JSFiddle看到完整的运行示例

          【讨论】:

            【解决方案8】:

            下面的代码将首先检查是否输入了两个输入以及两个输入是否都是数字,然后继续计算。 isNaN 函数用于检查数字。

            HTML 代码

            <input type="text" id="inputfield1" />
            <input type="text" id="inputfield2" />
            <button onclick="compare()">Compare</button>
            

            JAVASCRIPT

            function compare()
            {
                var variable1, variable2;
                try
                {
                     variable1 = parseInt(document.getElementById('inputfield1').value);
                 variable2 = parseInt(document.getElementById('inputfield2').value);
            
                 if (isNaN(variable1) || isNaN(variable2))
                 {
                 alert("Either or both of the inputs is not a number");
                 }
                 else if (variable1 > variable2) 
                 {
                     alert("The first variable is greater than the second.");
                 } 
                 else 
                 {
                     alert("The second variable is greater than or equal to the first one.");
                 }
               }
               catch (e)
               {
                    alert ('Exception Caught '+e);
               }
            };
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-12-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-25
              • 1970-01-01
              相关资源
              最近更新 更多