单击Javascript按钮,将值添加到文本框中

Javascript on button click add value to text box

本文关键字:文本 添加 Javascript 按钮 单击      更新时间:2023-09-26

这只是一个超级简单的javascript问题,但我无法了解它是如何工作的

需要将脚本输出到输入。

上的原始脚本http://jsfiddle.net/mYuRK/

谢谢!

var theTotal = 0;
$('button').click(function(){
   theTotal = Number(theTotal) + Number($(this).val());
    $('.tussenstand').text("Total: "+theTotal);        
});
$('.tussenstand').text("Total: "+theTotal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tussenstand">
<button value="1">1</button>
<button value="2">2</button>
<button value="4">4</button>
<button value="6">6</button>

由于您使用id作为输入,因此需要使用#而不是.作为选择器。对于input,您必须指定值。

因此,使用$('#tussenstand').val(代替$('.tussenstand').text(

var theTotal = 0;
$('button').click(function(){
   theTotal = Number(theTotal) + Number($(this).val());
    $('#tussenstand').val("Total: "+theTotal);        
});
$('#tussenstand').val("Total: "+theTotal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tussenstand">
<button value="1">1</button>
<button value="2">2</button>
<button value="4">4</button>
<button value="6">6</button>

在JS中将类选择器更改为id选择器,并使用val()而不是text()

var theTotal = 0;
$('button').click(function(){
   theTotal = Number(theTotal) + Number($(this).val());
    $('#tussenstand').val("Total: "+theTotal);        
});
$('#tussenstand').val("Total: "+theTotal);

val()是jQuery用来编辑/检索文本框的值。

使用此脚本:

<script>
        function insertTextInInputValue(buttonValueIs){
            var inputElementIs = document.getElementById("tussenstand");
            inputElementIs.value = inputElementIs.value + buttonValueIs;
        }
    </script>

使用HTML:

<input id="tussenstand">
<button onclick="insertTextInInputValue(1);">1</button>
<button onclick="insertTextInInputValue(2);">2</button>
<button onclick="insertTextInInputValue(3);">3</button>
<button onclick="insertTextInInputValue(4);">4</button>
<button onclick="insertTextInInputValue(5);">5</button>
<button onclick="insertTextInInputValue(6);">6</button>