Tye Lucas
Tye Lucas

Reputation: 107

Checkboxes to display total not working as planned

This is my JavaScript

<script type="text/javascript">
   $('#inputs input').change(function() {
   if (this.checked) {
   $span = $('<span></span>');
   $span.text(this.value);
   $('#results').append($span);
   }
   else {
   $('span:contains('+this.value+')', '#results').remove();
   }
   });
   </script>

This is my html

<div id="inputs">
<input type="checkbox" name="amount" value="50.00"></input>
<input type="checkbox" name="amount" value="20.00"></input>
<input type="checkbox" name="amount" value="15.00"></input>
<input type="checkbox" name="amount" value="10.00"></input>
<span>Total: $</span><span id="results"></span>

Since the checkboxes all have the same name it groups them so only one can be checked at a time, my question is: How to make this so the value for the first checkbox checked goes away when another checkbox is checked. This works only if you check a box then uncheck the same box, but if you check a box then check another you will see two values appear. I can not figure this out. Any help will be greatly appreciated. Thank you!

Upvotes: 0

Views: 54

Answers (1)

L777
L777

Reputation: 8457

this 'single choice" behavior belongs to radio input, not checkbox.

$('#inputs input').change(function() {
   if (this.checked) {
   $span = $('<span></span>');
   $span.text('$'+ this.value);
   $('#results').html($span);
   }
   else {
   $('span:contains('+this.value+')', '#results').remove();
   }
   });
body {
  background: skyblue;  
}
<div id="inputs">
<input type="radio" name="amount" value="50.00" id=i50>
<label for="i50">50</label>  
  
<input type="radio" name="amount" value="20.00" id=i20>
<label for="i20">20</label>
  
<input type="radio" name="amount" value="15.00" id=i15>
<label for="i15">15</label>
  
<input type="radio" name="amount" value="10.00" id=i10>
<label for="i10">10</label>
  
<br><br><span>Selected: </span><span id="results"></span></div>
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>

Upvotes: 1

Related Questions