I want only certain buttons to be displayed through jquery

I have a grid of buttons ehere user onpens up the gird by clicking on the (Open Grid) link and then clicking on a button in that grid. What will then happen is that a set of buttons appear below the text box depending on the button selected from the grid. So if user select button “1” then button “A” appears, if user selects button “2” then buttons “A” and “B” appears and so on.

Now this is done through jquery code below:

$(".gridBtns").click(function() {

   var clickedNumber = this.value;

   $('.answerBtns').each(function (index) {
      if (index < clickedNumber)
         $(this).show();
      else
         $(this).hide();
   });

});

But what I want to do is that if user selects button “True or False” from the grid, I want only the buttons “True” and “False” under the text box and if user selects “Yes or No” button from the gird, then I only want buttons “Yes” and “No” to display under the text box, How can this be do in my jquery code?

Also if user selects “True or False” button or “Yes or No” button, then I want the “Number of Answers” text box to disappear and display the span tag “N/A” only, does anyone know to do this in jquery.

Thanks and code is in jsfiddle, click here

One way to do this would be to split the job up in to two separate tasks.
The first task would be to check if the button is true/false, or yes/no, and to then show the appropriate buttons.

The first thing to do is to get rid of the inline event attribute


if (clickedNumber === 'True or False') {
    // show true/false buttons
    ...
} else if (clickedNumber === 'Yes or No') {
    // show yes/no buttons
    ...
} else {
    // show numeric buttons
    ...
}

Yes indeed. With a slight readjustment to the above conditional checks, both can be relatively easily catered for.


if (Number(clickedNumber)) {
    // show "Number of Answers" and remove any possible N/A span tag
    ...
    // show numeric buttons
    ...
} else {
    // hide "Number of Answers" and show N/A span tag
    ...
    if (clickedNumber === 'True or False') {
        // show true/false buttons
        ...
    } else if (clickedNumber === 'Yes or No') {
        // show yes/no buttons
        ...
    }
}

Now that the clickedNumber variable is going to contain more than just a number, and is in truth a string from this.value, have you considered renaming it to a more appropriate variable name, perhaps buttonValue or gridButton or something like that?

If so, with some refactoring to keep the related pieces of code together, it could be:


if (Number(buttonValue)) {
    // show numeric buttons
    ...
} else if (buttonValue === 'True or False') {
    // show true/false buttons
    ...
} else if (buttonValue === 'Yes or No') {
    // show yes/no buttons
    ...
}
if (Number(buttonValue)) {
    // show "Number of Answers" and remove any possible N/A span tag
    ...
} else {
    // hide "Number of Answers" and show N/A span tag
    ...
}