从两个字段计算值并在JavaScript的第三个字段中显示

时间:2019-06-29 19:27:47

标签: javascript textfield

我们如何从两个文本字段中获取价值,并执行一些操作后,如何在JavaScript的第三个文本字段中显示结果?

1 个答案:

答案 0 :(得分:0)

<html>
  <!-- input text boxes -->
  <input type="text" name="input-1">
  <input type="text" name="input-2">
  <input type="text" name="input-3">

  <!-- button to run calculation -->
  <button id="btn">Calculate</button>

  <!-- include jquery -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <script>

    // put in this function because you want to wait until the page loads
    $(function() {

      $('#btn').on('click', function(e) {

        // grab input from input 1 and input 2
        var val1 = $('input[value="input-1"]').val();
        var val2 = $('input[value="input-2"]').val();

        // we are just appending the values together to get val3 but you can do whatever you want for this part. I am just using this as an example.
        var val3 = val1 + ' ' + val2;

        // set value to input 3
        $('input[value="input-3"]').val(val3);
      });

    });

  </script>

</html>