Seppo Kuusela Seppo Kuusela - 2 months ago 6
CSS Question

jQuery / JS adding onClick button value into row

i am really new with JavaScript so i have been looking to make something with it. However i wanted to make that when you press X button it will print that button value into a div. The think how i want is that if you press one button and value is 1, it will print 1 to div and if you press 2nd button that value is 2 it will print 2 after the 1. So like 12 and not 3 (like in my JSFiddle down below)

I hope i can get help from here.

Here is my JSFiddle

JSFiddle



var theTotal = 0;
$('button').click(function(){
theTotal = Number(theTotal) + Number($(this).val());
$('.total').text(" "+theTotal);
});


#codebar {
background:black;
width:150px;
height:20px;
padding: 20px 20px;
}

.total {
color: red;
font-weight:bold;
font-size:50px;
margin-top:-18px !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button value="1">1</button>
<button value="2">2</button>
<button value="3">3</button>
<button value="4">4</button>
<button value="5">5</button>
<button value="6">6</button>
<button value="7">7</button>
<button value="8">8</button>
<button value="9">9</button>
<button value="10">10</button>

<br>

<div id="codebar">
<div class="total"></div>
</div>




Answer

You should .append() the button value as string

$('button').click(function(){
    $('.total').append($(this).val());        
});

JSFiddle

Comments