将值从按钮传递到 JavaScript 中的文本字段

Pass a Value from Button to Text Field in JavaScript

我正在尝试在单击按钮时将数字传递到文本字段。用户点击 "add to cart",2499 将添加到文本字段中已有的总数中。

<form name="cart">
    <input id="display" type="text" name="output" size="6" placeholder="0000"/>
<button id="scart" value="Add to Cart" onclick="addCart()" +='2499'"/>

<script type="text/javascript">

var total=""

function addCart(){
    document.getElementById('scart').value;
    total+= document.getElementById('display').value;
    console.log(total);
}

</script>

学习的时候感觉逻辑懂了,语法不懂

您有一些错误,您的报价不匹配,您没有关闭按钮标签。另外,为什么不在代码中加上2499呢?

这个怎么样:

<form name="cart">
    <input id="display" type="text" name="output" size="6" placeholder="0000"/>
    <button id="scart" value="Add to Cart" onclick="addCart()" > 
    </button>

    <script type="text/javascript">

    var total=""

    function addCart(){
        document.getElementById('scart').value;
        total+= document.getElementById('display').value + 2499;
        console.log(total);
    }

    </script>
</form>

不清楚您要做什么,所以我创建了一个 "cart" 按钮,其中输入的是您要添加到购物车的数量。

如果您多次按下按钮,我会打印出输入的数字和总数。

<input id="display" type="text" name="output" size="6" placeholder="0000" />
<button id="scart" type="button">Add to cart</button>

<script type="text/javascript">
  var total = 0;
  var display = document.querySelector('#display');
  var scart = document.querySelector('#scart');

  scart.addEventListener('click', function() {
    var str = display.value;
    var num = parseInt(str, 10);
    console.log('You entered the number: ', num);
    if (!isNaN(num)) {
      total += num;
    }
    console.log('The total is now: ', total);
  });
</script>

这里有很多错误:

首先,用一个好的指标 data-value 或其他

替换 +
<button id="scart" value="Add to Cart" onclick="addCart()" data-value="2499"/>

其次,在您的脚本中,您应该将 var total 设为 number 而不是 string

var total = 0;

最后,你的 addCart() 函数。

function addCart() {
    // I see you are trying to get the value of the clicked button so you need to store it as this does not do anything
    // document.getElementById('scart').value;
    var value = document.getElementById('scart').value;
    // Add it to total var;, you need to parseInt it as .value returns string
    total += parseInt(value);
    // put it on display
    document.getElementById('display').value = total;
}

希望对您有所帮助。

我想这就是你想要的。我为你做了一个代码笔:https://codepen.io/NeilGBK/pen/boGadz?editors=1111

   <form name="cart">
        <input id="display" type="text" name="output" size="6" placeholder="0000"/>   
    </form>
    <button id="scart" onclick="addCart(2499)">Add To Cart</button>

<script>
    function addCart(v){
        document.getElementById('display').value = v
        console.log(v);
        return false;
    }
</script>

我将数字传递给函数并简单地使用它来更改输入的值。我也将其记录到控制台