[英]Javascript on button click add value to text box
只是一個非常簡單的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').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>
將類選擇器更改為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.