Reputation: 458
<div class="container">
<div class="form-group">
<form>
<button>click to add/remove<input type="text" name="addfirst" value="10" readonly></button><br>
<button>click to add/remove<input type="text" name="addsecond" value="10" readonly></button><br>
<button>click to add/remove<input type="text" name="addthird" value="10" readonly></button><br>
<button>click to add/remove<input type="text" name="addfourth" value="10" readonly></button><br>
<label>total values</label>
<input type="text" name="total_ammount" value="50" readonly>
</form>
</div>
</div>
if i click button to add first input value which is 10 so it will addition with my total input field values if again the same button so substract the values. remaining field should do the same work also. how it is possible by using jquery please explain it.
Upvotes: 0
Views: 75
Reputation: 1280
Please Try the below code.,
function addValue(dhis){
var val=parseFloat(dhis.children().val()) // get the text box value
var total_ammount=parseFloat($('#total_ammount').val())+val
$('#total_ammount').val(total_ammount);
dhis.attr('onclick','subValue($(this))') // change the onclick function
}
function subValue(dhis){
var val=parseFloat(dhis.children().val()) // get the text box value
var total_ammount=parseFloat($('#total_ammount').val())-val
$('#total_ammount').val(total_ammount);
dhis.attr('onclick','addValue($(this))') // change the onclick function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="form-group">
<form>
<button type="button" onclick="addValue($(this))">click to add/remove<input type="text" name="addfirst" value="10" readonly></button><br>
<button type="button" onclick="addValue($(this))">click to add/remove<input type="text" name="addsecond" value="10" readonly></button><br>
<button type="button" onclick="addValue($(this))">click to add/remove<input type="text" name="addthird" value="10" readonly></button><br>
<button type="button" onclick="addValue($(this))">click to add/remove<input type="text" name="addfourth" value="10" readonly></button><br>
<label>total values</label>
<input type="text" name="total_ammount" id="total_ammount" value="50" readonly>
</form>
</div>
</div>
Upvotes: 3