I need to add three more buttons to this script for a total of 5.
I first made the script for two buttons, but I now need to add three more.
Would I only be concerned with this portion? Is this the only area I need to change?
var varval = '';
if ($(this).hasClass('button-toggle-on')) {
varval = $(this).hasClass('gnF') ? 'Female' : 'Male';
Link: http://jsfiddle.net/9cr4F/9/
Here is my script:
$(function() {
var $buttons = $("input[type='button']");
$buttons.click(function() {
$(this).parent().siblings('.bx, #bxGender .gender').css({'background':'#2F2F2F','color':'#fff'});
$buttons.not(this).removeClass('button-toggle-on');
$(this).toggleClass('button-toggle-on').attr('style','');
var varval = '';
if ($(this).hasClass('button-toggle-on')) {
varval = $(this).hasClass('gnF') ? 'Female' : 'Male';
$(this).siblings('input[type="button"]').css('background-position','0 -180px');
}
else {
$(this).siblings('input[type="button"]').attr('style','');
$(this).parent().siblings('.bx').attr('style','');
}
$("#gender").val(varval);
});
});
From what I’m getting from your code, you have two buttons right now:
MaleandFemale. When you click one, it changes some#genderelement’s value to either Male or Female, depending on whether or not it has some class.I imagine that you want to add three more possible values to gender, hence the three new buttons. If that’s the case, then there’s a critical place in your code that you will have to modify:
Right now, you’re using a ternary operator to determine the correct value. That’s going to get dirty if you’re looking at five possible values instead of the original two.
Barring any changes in your HTML, I’d suggest you use a
switchinstead.But regarding your real question
is that the only thing I need to change?, I’d have to say that from the looks of it, you can really make your code so much simpler if you set up your HTML right.Something like:
… makes it so much easier to just do this instead:
Best of all, that works, no matter how many buttons you have.