[英]Javascript on button click add value to text box
Just a super simple javascript question, but i cannot find out how it works 只是一个非常简单的JavaScript问题,但我无法找出其工作原理
Need to get script output to the input. 需要获取脚本输出到输入。
original script on http://jsfiddle.net/mYuRK/ http://jsfiddle.net/mYuRK/上的原始脚本
Thanks! 谢谢!
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>
Since you're using an id for the input you need to use #
instead of .
由于您在输入中使用ID,因此需要使用
#
而不是.
for the selector. 选择器。 And for
input
you have to assign the value. 对于
input
您必须分配值。
So instead of $('.tussenstand').text(
use $('#tussenstand').val(
. 所以不要使用
$('.tussenstand').text(
使用$('#tussenstand').val(
。
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>
Change the class selector to an id selector in your JS, and use val()
instead of text()
. 将类选择器更改为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()
is what jQuery uses to edit/retrieve the value of a textbox. val()
是jQuery用于编辑/检索文本框值的工具。
Use this SCRIPT: 使用此脚本:
<script>
function insertTextInInputValue(buttonValueIs){
var inputElementIs = document.getElementById("tussenstand");
inputElementIs.value = inputElementIs.value + buttonValueIs;
}
</script>
with the HTML: 使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.