var array = [];
$('input').click(function(){
var value = this.value;
if (array.indexOf(value) > -1) {
array.splice(array.indexOf(value));
$(this).next('span').html('');
return false;
}
array.push(value);
$(this).next('span').html(array.indexOf(value));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='button' value="x">
<span></span>
</div>
<div>
<input type='button' value="y">
<span></span>
</div>
In my Script here, I insert the index in the next span after input, So when you click x you get 0 and When you click y you get 1 and viceversa, The problem is When I click again on x which has index = 0,
What I expect is for the span of y to change to 0 instead of 1 since the key place changed after removing x index,
But that doesn't happen and the span stays 1 But if clicked it again, It changes to 0, How do I fix this problem?
EDIT: Added jQuery tag
spanafteryto change it's text. You are only ever telling the spans after the clicked input to change. If you want both to update, you'll need to update both.