简体   繁体   中英

Javascript on button click add value to text box

Just a super simple javascript question, but i cannot find out how it works

Need to get script output to the input.

original script on 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 . for the selector. And for input you have to assign the value.

So instead of $('.tussenstand').text( use $('#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() .

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.

Use this SCRIPT:

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

with the 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM