Reputation: 59
Essentially, I am trying to have 3 buttons with 3 different values - but only one shown at at time. Every time a button is clicked it disappears and the following button shows up in the same button location. Sort of a loop that goes through the 3 buttons every click.
Default Start: [Button 1 - Value A]
Button 1.clicked -> [Button 2 - Value B]
Button 2.clicked -> [Button 3 - Value C]
Button 3.clicked -> [Button 1 - Value A]
Truly appreciate if anyone cares to share how to achieve this with JavaScript.
The idea is similar to the play & pause buttons the change every time clicked. I wish to add a third element to the cycle.
Upvotes: 0
Views: 1073
Reputation: 1675
On a cleaner and simpler approach
HTML
<div>
<button class="button button1 active">Button1</button>
<button class="button button2">Button2</button>
<button class="button button3">Button3</button>
</div>
CSS
.button{
display:none;
}
.button.active{
display:block;
}
Javascript
$(document).ready(function(){
$('.button').on('click',function(){
var buttons = ('.button').length;
var thisIndex = $('.button').index(this);
var next = thisIndex < 2 ? thisIndex+1 : 0;
$('.button.active').removeClass('active');
$('.button').eq(next).addClass('active');
});
});
And here is a demo jsfiddle http://jsfiddle.net/ajaaibu/phsrtpyy/
Upvotes: 0
Reputation: 2565
I think it makes sense If you keep your button and simply change only its value:
$(document).ready(function() {
var buttons = ["A", "B", "C"]; //All your buttons values here
$(".insert_button").append("<input class='Button' type='button' value='A'></input>");
$('.Button').click(function() {
var next = buttons[($.inArray($(this).val(), buttons) + 1) % buttons.length]; //get next element in array
$(this).val(next);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="insert_button"></div>
Upvotes: 0
Reputation: 701
Look at my following example:
function clickMe(element) {
element = $(element);
var next = element.attr('data-rel');
//alert(element.attr('data-text')); //show value
element.hide(); //hide element
$('button.' + next).show(); //show next button
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="button-1" data-rel="button-2" data-text="Value 1" onclick="clickMe(this);">Button 1</button>
<button style="display:none;" class="button-2" data-rel="button-3" data-text="Value 2" onclick="clickMe(this);">Button 2</button>
<button style="display:none;" class="button-3" data-rel="button-1" data-text="Value 3" onclick="clickMe(this);">Button 3</button>
Upvotes: 0