Reputation: 1883
In this example, I am trying to increase value of span
by selecting an option
, but I want decrease current value if change option.
$('select').change(function() {
var span = +$('span').text();
var val = +$(this).find('option:selected').attr('data-val');
var nextNumber = Math.abs(span + val);
$('span').text(nextNumber);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option data-val="15">Item 1</option>
<option data-val="25">Item 2</option>
<option data-val="10">Item 3</option>
</select>
<span>150</span>
For example, you select Item 3, span text going to set 160, right? now want to change this option, select Item 1, it going to set 175, but I want to increase by new value, it should be 165. I want to decrease previously value, just increase by new selected option.
Another example, If you select Item 1, span value should be 165, if Item 2, 175, If item 3, 160.
GOAL: Increase span
text just by selected option, and remove/decrease previous values.
This is what I have done so far but have no idea to decrease previous value, any idea. Thanks for advance.
Upvotes: 0
Views: 59
Reputation: 800
You just have to keep the initial value of the span somewhere:
$('select').change(function() {
var span = +$('span').attr('data-initial-val');
var val = +$(this).find('option:selected').attr('data-val');
var nextNumber = Math.abs(span + val);
$('span').text(nextNumber);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option data-val="15">Item 1</option>
<option data-val="25">Item 2</option>
<option data-val="10">Item 3</option>
</select>
<span data-initial-val="150">150</span>
In the case of another input's that change the span text :
$('select').change(function() {
var span = +$('span').attr('data-initial-value');
var val = +$(this).find('option:selected').attr('data-val');
var nextNumber = Math.abs(span + val);
$('span').text(nextNumber);
});
$('input[type="checkbox"]').click(function() {
var span = + $('span').attr('data-initial-value');
var val = +$(this).val();
var selecNumber = +$('select').find('option:selected').attr('data-val');
if ($(this).prop('checked') === true) {
var nextNumber = Math.abs(span + val);
$('span').text(nextNumber + selecNumber);
$('span').attr('data-initial-value', nextNumber);
} else {
var nextNumber = Math.abs(span - val);
$('span').attr('data-initial-value', nextNumber);
$('span').text(nextNumber + selecNumber);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option data-val="15">Item 1</option>
<option data-val="25">Item 2</option>
<option data-val="10">Item 3</option>
</select>
<span data-initial-value="150">150</span>
<input type="checkbox" value="22" />
<input type="checkbox" value="25" />
<input type="checkbox" value="5" />
Upvotes: 5