0

output of my code

<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.

0

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

3 Comments

you are welcome. please mark it as helpful. thank you.
JIJOMON K.A 's answer is very good. @md server you can use also pure javascript without jquery for this solution.
@Ferdinando Thank you, You can appreciate me with a up vote :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.