I need to put value from button to text place.I do this .
text($(button).val());
But it just replaces the text I need when I need just to +
this value.Like value is 5
then then again + 5
so it will be 55
.
Instead of:
.text($(button).val());
You may use:
.text( function ) : where function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
An example:
$('#btn').on('click', function(e) { var val = $(this).val(); $('#txt').text(function(idx, txt) { return txt + val; }); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="txt"></p> <button id="btn" value="5">Click Me</button>
If you're looking to get the contents of a button and then add to it, you need to do the following. Let's say the button is as follows:
<button id="someButton">5</button>
You want to add 5 to it so the button says 10.
var buttonText = parseInt($("#someButton").text()) + 5; //results in 10
$("#someButton").text(buttonText);
As you can see, I used parseInt
to ensure the number was seen an integer so you could perform addition on it.
function addText () { document.getElementById('paragraph').innerHTML += $('#buttonID').val(); }
Try this. This +=
to the innerHTML as opposed to re-assigning. It is a JavaScript/jQuery hybrid, which I hope is okay, but there is also this pure jQuery method that uses the .append() method that @Patrick Evans mentioned.
$(document).ready(function () { $('#paragraph').append($('#buttonID').val()); });
Hope this helped.
If you're looking to just append values:
<button class="display-value">5</button>
<button id="plus">+</button>
Now you can do this in jQuery:
$('#plus').on('click' , () => {
let val = $('.display-value').text();
$('.display-value').text((val + val));
return false;
});
If you're looking to perform a mathematical operation then, you will have to use parseInt
.
$('#plus').on('click' , () => {
let val = parseInt($('.display-value').text());
$('.display-value').text((val + val));
return false;
});
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.