Reputation: 99
I am trying to write a variable that holds the main value of the paragraph tag as seen here:
<button id="button">random words</button>
<p id="inc">0</p>
<script>
$(document).ready(function(){
$('#button').on("click", function(){
var oldVal = $("#inc")
$('#inc').text( oldVal + 1)
});
});
</script>
How do I turn the '#inc' into a number so i can do a + 1 increment?
Upvotes: 1
Views: 2430
Reputation: 1096
update your code with below code you will get what you want
<script>
$(document).ready(function(){
$('#button').on("click", function(){
var oldVal = parseInt($("#inc").text());
$('#inc').text( oldVal + 1)
});
});
</script>
Actually there is single mistake in your code which is
var oldVal = $("#inc")
must be replace by
var oldVal = parseInt($("#inc").text());
Upvotes: 0
Reputation: 82241
You can use callback text function to accept old text and modify it with new.
You would also need to parse the old value into integer for incrementing it:
$('#button').on("click", function(){
$('#inc').text(function(i,oldVal){
return parseInt(oldVal,10) + 1 ;
});
});
Upvotes: 1
Reputation: 388316
$("#inc")
returns a jQuery obeject not its content, you can use .text() to get its content then increment it. Note that .text()
will return a string value so you need to convert that to a numeric value before trying to add 1
$(document).ready(function() {
$('#button').on("click", function() {
$("#inc").text(function(i, text) {
return +text + 1 || 0
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button">random words</button>
<p id="inc">0</p>
Upvotes: 0